Class FieldUtils

  • All Implemented Interfaces:
    Utils

    public abstract class FieldUtils
    extends java.lang.Object
    implements Utils
    The Java Reflection Field Utility class
    Since:
    1.0.0
    Author:
    Mercy
    • Method Summary

      All Methods Static Methods Concrete Methods 
      Modifier and Type Method Description
      static void assertFieldMatchType​(java.lang.Object instance, java.lang.String fieldName, java.lang.Class<?> expectedType)
      Asserts that the type of the specified field in the given object or class matches or is a subtype of the expected type.
      static java.util.Set<java.lang.reflect.Field> findAllDeclaredFields​(java.lang.Class<?> declaredClass, java.util.function.Predicate<? super java.lang.reflect.Field>... fieldFilters)
      Find and return all declared fields in the class hierarchy, optionally filtered by one or more predicates.
      static java.util.Set<java.lang.reflect.Field> findAllFields​(java.lang.Class<?> declaredClass, java.util.function.Predicate<? super java.lang.reflect.Field>... fieldFilters)
      Find and return all accessible fields in the class hierarchy, optionally filtered by one or more predicates.
      static java.lang.reflect.Field findField​(java.lang.Class<?> klass, java.lang.String fieldName)
      Finds a Field in the specified class by its name.
      static java.lang.reflect.Field findField​(java.lang.Class<?> klass, java.lang.String fieldName, java.lang.Class<?> fieldType)
      Find the declared Field by its name and type.
      static java.lang.reflect.Field findField​(java.lang.Class<?> klass, java.lang.String fieldName, java.util.function.Predicate<? super java.lang.reflect.Field>... predicates)
      Find the declared Field by its name and apply additional filtering conditions.
      static java.lang.reflect.Field findField​(java.lang.Object object, java.lang.String fieldName)
      Find the specified object's declared Field by its name.
      static java.lang.reflect.Field getDeclaredField​(java.lang.Class<?> declaredClass, java.lang.String fieldName)
      Retrieves the declared field with the specified name from the given class.
      static <V> V getFieldValue​(java.lang.Object instance, java.lang.reflect.Field field)
      Retrieves the value of the specified Field from the given object instance.
      static <V> V getFieldValue​(java.lang.Object instance, java.lang.String fieldName)
      Retrieves the value of a field with the specified name from the given object instance.
      static <V> V getFieldValue​(java.lang.Object instance, java.lang.String fieldName, java.lang.Class<V> fieldType)
      Retrieves the value of a field with the specified name and type from the given object instance.
      static <V> V getFieldValue​(java.lang.Object instance, java.lang.String fieldName, V defaultValue)
      Retrieves the value of a field with the specified name from the given object instance, returning the provided default value if the field is not found or its value is null.
      static <T> T getStaticFieldValue​(java.lang.Class<?> klass, java.lang.String fieldName)
      Retrieves the value of a static field from the specified class.
      static <T> T getStaticFieldValue​(java.lang.reflect.Field field)
      Retrieves the value of a static field.
      static <V> V setFieldValue​(java.lang.Object instance, java.lang.reflect.Field field, V value)
      Sets the value of the specified Field in the given object instance.
      static <V> V setFieldValue​(java.lang.Object instance, java.lang.String fieldName, V value)
      Sets the value of a field with the specified name in the given object instance.
      static <V> V setStaticFieldValue​(java.lang.Class<?> klass, java.lang.String fieldName, V fieldValue)
      Sets the value of a static field in the specified class.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Method Detail

      • findField

        @Nullable
        public static java.lang.reflect.Field findField​(java.lang.Object object,
                                                        java.lang.String fieldName)
        Find the specified object's declared Field by its name.

        Example Usage

        
         class Example {
             private String testField;
         }
        
         Example instance = new Example();
         Field field = FieldUtils.findField(instance, "testField");
         if (field != null) {
             System.out.println("Field found: " + field.getName());
         } else {
             System.out.println("Field not found.");
         }
         
        Parameters:
        object - the object whose class is to be examined
        fieldName - the name of the field to find
        Returns:
        the Field object if found; otherwise, null
      • findField

        @Nullable
        public static java.lang.reflect.Field findField​(java.lang.Class<?> klass,
                                                        java.lang.String fieldName)
        Finds a Field in the specified class by its name.

        This method recursively searches for the field in the given class and its superclasses until it finds the field or reaches the top of the class hierarchy (i.e., the Object class).

        Example Usage

        
         class Example {
             private String testField;
         }
        
         Field field = FieldUtils.findField(Example.class, "testField");
         if (field != null) {
             System.out.println("Field found: " + field.getName());
         } else {
             System.out.println("Field not found.");
         }
         
        Parameters:
        klass - The class to examine for the field
        fieldName - The name of the field to find
        Returns:
        The found Field, or null if no such field exists
        Throws:
        java.lang.RuntimeException - if an exception occurs during field lookup, typically wrapped as an unchecked exception
      • findField

        @Nullable
        public static java.lang.reflect.Field findField​(java.lang.Class<?> klass,
                                                        java.lang.String fieldName,
                                                        java.lang.Class<?> fieldType)
        Find the declared Field by its name and type.

        This method searches for a field with the specified name and type in the given class. If the field is not found, it recursively checks the superclasses until it finds a matching field or reaches the top of the class hierarchy.

        Example Usage

        
         class Example {
             private String testField;
         }
        
         Field field = FieldUtils.findField(Example.class, "testField", String.class);
         if (field != null) {
             System.out.println("Field found: " + field.getName());
         } else {
             System.out.println("Field not found.");
         }
         
        Parameters:
        klass - The class to examine for the field
        fieldName - The name of the field to find
        fieldType - The expected type of the field
        Returns:
        The found Field, or null if no such field exists
      • findField

        @Nullable
        public static java.lang.reflect.Field findField​(java.lang.Class<?> klass,
                                                        java.lang.String fieldName,
                                                        java.util.function.Predicate<? super java.lang.reflect.Field>... predicates)
        Find the declared Field by its name and apply additional filtering conditions.

        This method searches for a field with the specified name in the given class. If the field is found, it applies the provided predicates to further filter the field. If any predicate evaluates to false, this method returns null.

        Example Usage

        
         class Example {
             private String testField;
         }
        
         // Find field and ensure it's private
         Field field = FieldUtils.findField(Example.class, "testField", f -> Modifier.isPrivate(f.getModifiers()));
         if (field != null) {
             System.out.println("Field found and passed all filters.");
         } else {
             System.out.println("Field not found or did not pass filters.");
         }
         
        Parameters:
        klass - The class to examine for the field
        fieldName - The name of the field to find
        predicates - One or more predicates used to filter the found field
        Returns:
        The found field that satisfies all the provided predicates, or null if no such field exists
      • getStaticFieldValue

        @Nullable
        public static <T> T getStaticFieldValue​(java.lang.Class<?> klass,
                                                java.lang.String fieldName)
        Retrieves the value of a static field from the specified class.

        This method attempts to find the declared field by name in the given class and then retrieves its value. If the field is not found or is not accessible, an appropriate exception may be thrown.

        Example Usage

        
         class Example {
             private static String testField = "Hello, World!";
         }
        
         String value = FieldUtils.getStaticFieldValue(Example.class, "testField");
         System.out.println("Field value: " + value);  // Output: Field value: Hello, World!
         
        Type Parameters:
        T - The type of the field value
        Parameters:
        klass - The class containing the static field
        fieldName - The name of the static field to retrieve
        Returns:
        The value of the static field, or null if the field could not be accessed or was not found
      • getStaticFieldValue

        @Nullable
        public static <T> T getStaticFieldValue​(java.lang.reflect.Field field)
        Retrieves the value of a static field.

        This method gets the value of the specified static field. If the field is not accessible, an attempt will be made to make it accessible.

        Example Usage

        
         class Example {
             private static String testField = "Static Value";
         }
        
         Field field = FieldUtils.findField(Example.class, "testField");
         String value = FieldUtils.getStaticFieldValue(field);
         System.out.println("Field value: " + value);  // Output: Field value: Static Value
         
        Type Parameters:
        T - The type of the field value
        Parameters:
        field - The Field object representing the static field
        Returns:
        The value of the static field, or null if the field could not be accessed or was not found
      • setStaticFieldValue

        @Nullable
        public static <V> V setStaticFieldValue​(java.lang.Class<?> klass,
                                                java.lang.String fieldName,
                                                V fieldValue)
        Sets the value of a static field in the specified class.

        This method finds the declared field by name in the given class and sets its value to the provided value. If the field is not found or cannot be accessed, an appropriate exception may be thrown.

        Example Usage

        
         class Example {
             private static String testField = "Original Value";
         }
        
         // Set the static field's value
         FieldUtils.setStaticFieldValue(Example.class, "testField", "New Value");
        
         // Verify the change
         String value = FieldUtils.getStaticFieldValue(Example.class, "testField");
         System.out.println("Updated field value: " + value);  // Output: Updated field value: New Value
         
        Type Parameters:
        V - The type of the field value
        Parameters:
        klass - The class containing the static field
        fieldName - The name of the static field to set
        fieldValue - The value to assign to the static field
        Returns:
        The previous value of the static field, or null if the field could not be accessed or was not found
      • findAllFields

        @Nonnull
        public static java.util.Set<java.lang.reflect.Field> findAllFields​(java.lang.Class<?> declaredClass,
                                                                           java.util.function.Predicate<? super java.lang.reflect.Field>... fieldFilters)
        Find and return all accessible fields in the class hierarchy, optionally filtered by one or more predicates.

        This method collects all public fields from the specified class and its superclasses (including interfaces), and applies optional filtering conditions to select only the desired fields.

        Example Usage

        
         class Example {
             public int publicField;
         }
        
         Set<Field> fields = FieldUtils.findAllFields(Example.class);
         for (Field field : fields) {
             System.out.println("Found field: " + field.getName());
         }
         

        Filtering Fields

        
         Set<Field> stringFields = FieldUtils.findAllFields(Example.class,
             field -> field.getType().equals(String.class));
         
        Parameters:
        declaredClass - The class whose fields are to be searched
        fieldFilters - Optional predicates used to filter the found fields
        Returns:
        A set of fields that match the given criteria, preserving insertion order
      • findAllDeclaredFields

        @Nonnull
        public static java.util.Set<java.lang.reflect.Field> findAllDeclaredFields​(java.lang.Class<?> declaredClass,
                                                                                   java.util.function.Predicate<? super java.lang.reflect.Field>... fieldFilters)
        Find and return all declared fields in the class hierarchy, optionally filtered by one or more predicates.

        This method collects all declared fields from the specified class and its superclasses (including interfaces), and applies optional filtering conditions to select only the desired fields.

        Example Usage

        
         class Example {
             private String privateField;
             public int publicField;
         }
        
         Set<Field> fields = FieldUtils.findAllDeclaredFields(Example.class);
         for (Field field : fields) {
             System.out.println("Found field: " + field.getName());
         }
         

        Filtering Fields

        
         Set<Field> privateFields = FieldUtils.findAllDeclaredFields(Example.class,
             field -> Modifier.isPrivate(field.getModifiers()));
         
        Parameters:
        declaredClass - The class whose declared fields are to be searched
        fieldFilters - Optional predicates used to filter the found fields
        Returns:
        A set of declared fields that match the given criteria, preserving insertion order
      • getDeclaredField

        @Nullable
        public static java.lang.reflect.Field getDeclaredField​(java.lang.Class<?> declaredClass,
                                                               java.lang.String fieldName)
        Retrieves the declared field with the specified name from the given class.

        This method uses reflection to find the field and wraps any exceptions thrown during execution in an unchecked exception.

        Example Usage

        
         class Example {
             private String exampleField;
         }
        
         Field field = FieldUtils.getDeclaredField(Example.class, "exampleField");
         if (field != null) {
             System.out.println("Field found: " + field.getName());
         } else {
             System.out.println("Field not found.");
         }
         
        Parameters:
        declaredClass - The class containing the declared field
        fieldName - The name of the field to retrieve
        Returns:
        The Field object representing the declared field
        Throws:
        java.lang.RuntimeException - if an error occurs while retrieving the field, typically wrapped as an unchecked exception
      • getFieldValue

        @Nullable
        public static <V> V getFieldValue​(java.lang.Object instance,
                                          java.lang.String fieldName)
                                   throws java.lang.IllegalStateException,
                                          java.lang.IllegalArgumentException
        Retrieves the value of a field with the specified name from the given object instance.

        This method finds the declared field by its name in the class of the provided instance and retrieves its value. If the field is not found or cannot be accessed, an appropriate exception will be thrown.

        Example Usage

        
         class Example {
             private String exampleField = "Hello, Reflection!";
         }
        
         Example instance = new Example();
         String value = FieldUtils.getFieldValue(instance, "exampleField");
         System.out.println("Field value: " + value);  // Output: Field value: Hello, Reflection!
         
        Type Parameters:
        V - The type of the field value
        Parameters:
        instance - The object instance from which to retrieve the field value
        fieldName - The name of the field whose value is to be retrieved
        Returns:
        The value of the field, or null if the field could not be accessed or was not found
        Throws:
        java.lang.IllegalStateException - if this Field object is enforcing Java language access control and the underlying field is inaccessible
        java.lang.IllegalArgumentException - if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof)
      • getFieldValue

        @Nullable
        public static <V> V getFieldValue​(java.lang.Object instance,
                                          java.lang.String fieldName,
                                          V defaultValue)
                                   throws java.lang.IllegalStateException,
                                          java.lang.IllegalArgumentException
        Retrieves the value of a field with the specified name from the given object instance, returning the provided default value if the field is not found or its value is null.

        This method finds the declared field by its name in the class of the provided instance and retrieves its value. If the field is not found or cannot be accessed, an appropriate exception will be thrown.

        Example Usage

        
         class Example {
             private String exampleField;
         }
        
         Example instance = new Example();
         String value = FieldUtils.getFieldValue(instance, "exampleField", "default");
         System.out.println("Field value: " + value);  // Output: Field value: default
         
        Type Parameters:
        V - The type of the field value
        Parameters:
        instance - The object instance from which to retrieve the field value
        fieldName - The name of the field whose value is to be retrieved
        defaultValue - The default value to return if the field's value is null
        Returns:
        The value of the field if found and not null; otherwise, the defaultValue
        Throws:
        java.lang.IllegalStateException - If this Field object is enforcing Java language access control and the underlying field is inaccessible
        java.lang.IllegalArgumentException - If the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof)
      • getFieldValue

        @Nullable
        public static <V> V getFieldValue​(java.lang.Object instance,
                                          java.lang.String fieldName,
                                          java.lang.Class<V> fieldType)
                                   throws java.lang.IllegalStateException,
                                          java.lang.IllegalArgumentException
        Retrieves the value of a field with the specified name and type from the given object instance.

        This method finds the declared field by its name and ensures it matches the provided field type. If the field is not found or its type does not match, null is returned.

        Example Usage

        
         class Example {
             private String exampleField = "Typed Value";
         }
        
         Example instance = new Example();
         String value = FieldUtils.getFieldValue(instance, "exampleField", String.class);
         System.out.println("Field value: " + value);  // Output: Field value: Typed Value
         
        Type Parameters:
        V - The expected type of the field value
        Parameters:
        instance - The object instance from which to retrieve the field value
        fieldName - The name of the field whose value is to be retrieved
        fieldType - The expected type of the field
        Returns:
        The value of the field if found and of the correct type; otherwise, null
        Throws:
        java.lang.IllegalStateException - if this Field object is enforcing Java language access control and the underlying field is inaccessible
        java.lang.IllegalArgumentException - if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof)
      • getFieldValue

        @Nullable
        public static <V> V getFieldValue​(java.lang.Object instance,
                                          java.lang.reflect.Field field)
                                   throws java.lang.IllegalStateException,
                                          java.lang.IllegalArgumentException
        Retrieves the value of the specified Field from the given object instance.

        This method accesses the field's value using reflection. If the field is not accessible, an attempt will be made to make it accessible. If access fails, an exception will be thrown.

        Example Usage

        
         class Example {
             private String exampleField = "Reflection Value";
         }
        
         Example instance = new Example();
         Field field = FieldUtils.findField(instance, "exampleField");
         String value = FieldUtils.getFieldValue(instance, field);
         System.out.println("Field value: " + value);  // Output: Field value: Reflection Value
         

        Handling Null Fields

        
         Field nullField = null;
         String value = FieldUtils.getFieldValue(instance, nullField);
         System.out.println("Field value: " + value);  // Output: Field value: null
         
        Type Parameters:
        V - The type of the field value
        Parameters:
        instance - The object instance from which to retrieve the field value
        field - The Field object representing the field to retrieve
        Returns:
        The value of the field if found and accessible; otherwise, null
        Throws:
        java.lang.IllegalStateException - if this Field object is enforcing Java language access control and the underlying field is inaccessible
        java.lang.IllegalArgumentException - if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof)
      • setFieldValue

        @Nullable
        public static <V> V setFieldValue​(java.lang.Object instance,
                                          java.lang.String fieldName,
                                          V value)
                                   throws java.lang.IllegalStateException,
                                          java.lang.IllegalArgumentException
        Sets the value of a field with the specified name in the given object instance.

        This method finds the declared field by its name in the class of the provided instance and sets its value to the provided value. If the field is not found or cannot be accessed, an appropriate exception will be thrown.

        Example Usage

        
         class Example {
             private String exampleField = "Original Value";
         }
        
         Example instance = new Example();
         // Get the original value
         String originalValue = FieldUtils.getFieldValue(instance, "exampleField");
         System.out.println("Original value: " + originalValue);  // Output: Original value: Original Value
        
         // Set a new value using setFieldValue
         String previousValue = FieldUtils.setFieldValue(instance, "exampleField", "New Value");
         System.out.println("Previous value: " + previousValue);  // Output: Previous value: Original Value
         System.out.println("Updated value: " + FieldUtils.getFieldValue(instance, "exampleField"));
         // Output: Updated value: New Value
         
        Type Parameters:
        V - The type of the field value
        Parameters:
        instance - The object instance whose field value is to be set
        fieldName - The name of the field whose value is to be set
        value - The new value to assign to the field
        Returns:
        The previous value of the field before it was updated, or null if the field could not be accessed or was not found
        Throws:
        java.lang.IllegalStateException - if this Field object is enforcing Java language access control and the underlying field is inaccessible
        java.lang.IllegalArgumentException - if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof)
      • setFieldValue

        @Nullable
        public static <V> V setFieldValue​(java.lang.Object instance,
                                          java.lang.reflect.Field field,
                                          V value)
                                   throws java.lang.IllegalStateException,
                                          java.lang.IllegalArgumentException
        Sets the value of the specified Field in the given object instance.

        This method accesses and modifies the field's value using reflection. If the field is not accessible, an attempt will be made to make it accessible. If access fails, an exception will be thrown.

        Example Usage

        
         class Example {
             private String exampleField = "Initial Value";
         }
        
         Example instance = new Example();
         Field field = FieldUtils.findField(instance, "exampleField");
        
         // Get the original value
         String originalValue = FieldUtils.getFieldValue(instance, field);
         System.out.println("Original value: " + originalValue);  // Output: Original value: Initial Value
        
         // Set a new value using setFieldValue
         String previousValue = FieldUtils.setFieldValue(instance, field, "Updated Value");
         System.out.println("Previous value: " + previousValue);  // Output: Previous value: Initial Value
         System.out.println("New value: " + FieldUtils.getFieldValue(instance, field));  // Output: New value: Updated Value
         

        Handling Null Fields

        
         Field nullField = null;
         String previousValue = FieldUtils.setFieldValue(instance, nullField, "New Value");
         System.out.println("Previous value: " + previousValue);  // Output: Previous value: null
         
        Type Parameters:
        V - The type of the field value
        Parameters:
        instance - The object instance whose field value is to be modified
        field - The Field object representing the field to modify
        value - The new value to assign to the field
        Returns:
        The previous value of the field before modification, or null if the field was not found or inaccessible
        Throws:
        java.lang.IllegalStateException - If this Field object is enforcing Java language access control and the underlying field is inaccessible
        java.lang.IllegalArgumentException - If the specified object is not an instance of the class or interface declaring the underlying field
      • assertFieldMatchType

        public static void assertFieldMatchType​(java.lang.Object instance,
                                                java.lang.String fieldName,
                                                java.lang.Class<?> expectedType)
                                         throws java.lang.IllegalArgumentException
        Asserts that the type of the specified field in the given object or class matches or is a subtype of the expected type.

        This method is useful when validating field types at runtime, especially when working with reflection-based operations, such as injection frameworks, dynamic proxies, or generic utilities.

        Example Usage

        
         class Example {
             private String testField;
         }
        
         Example instance = new Example();
         FieldUtils.assertFieldMatchType(instance, "testField", CharSequence.class);
         // This will pass because String is a subclass of CharSequence
         

        Failure Case

        
         try {
             FieldUtils.assertFieldMatchType(instance, "testField", Integer.class);
         } catch (IllegalArgumentException e) {
             System.out.println("Caught exception: " + e.getMessage());
             // Output: Caught exception: The type['java.lang.String'] of field['testField'] in Class['Example'] can't match expected type['java.lang.Integer']
         }
         
        Parameters:
        instance - the object whose class is to be examined, or directly a Class object
        fieldName - the name of the field to check
        expectedType - the expected type the field should be or extend/implement
        Throws:
        java.lang.IllegalArgumentException - if the field's actual type does not match or is not assignable to the expected type