Class FieldUtils


  • public class FieldUtils
    extends Object
    Shameless copy from Apache commons lang and then modified to keep only the interesting stuff for AssertJ. Utilities for working with fields by reflection. Adapted and refactored from the dormant [reflect] Commons sandbox component.

    The ability is provided to break the scoping restrictions coded by the programmer. This can allow fields to be changed that shouldn't be. This facility should be used with care.

    • Constructor Detail

      • FieldUtils

        public FieldUtils()
    • Method Detail

      • getField

        static Field getField​(Class<?> cls,
                              String fieldName,
                              boolean forceAccess)
                       throws IllegalAccessException
        Gets an accessible Field by name breaking scope if requested. Superclasses/interfaces will be considered.
        Parameters:
        cls - the class to reflect, must not be null
        fieldName - the field name to obtain
        forceAccess - whether to break scope restrictions using the setAccessible method. False will only match public fields.
        Returns:
        the Field object
        Throws:
        IllegalArgumentException - if the class or field name is null
        IllegalAccessException - if field exists but is not public
      • readField

        private static Object readField​(Field field,
                                        Object target,
                                        boolean forceAccess)
                                 throws IllegalAccessException
        Reads a Field.
        Parameters:
        field - the field to use
        target - the object to call on, may be null for static fields
        forceAccess - whether to break scope restrictions using the setAccessible method.
        Returns:
        the field value
        Throws:
        IllegalArgumentException - if the field is null
        IllegalAccessException - if the field is not made accessible
      • readField

        static Object readField​(Object target,
                                String fieldName,
                                boolean forceAccess)
                         throws IllegalAccessException
        Reads the named field. Superclasses will be considered.
        Parameters:
        target - the object to reflect, must not be null
        fieldName - the field name to obtain
        forceAccess - whether to break scope restrictions using the setAccessible method. False will only match public fields.
        Returns:
        the field value
        Throws:
        IllegalArgumentException - if the class or field name is null
        IllegalAccessException - if the named field is not made accessible