In Java reflection, both getFields() and getDeclaredFields() are methods used to retrieve fields (variables) from a class. However, they differ in the type of fields they retrieve and their accessibility:
getFields():
getFields() returns an array of public fields (including public static and public final) from the class and its superclasses.getDeclaredFields():
getDeclaredFields() returns an array of all fields (including public, private, protected, package-private, static, and final) declared in the class where the method is called.Here's an example to illustrate the difference:
import java.lang.reflect.Field; class Parent { public int publicField; private int privateField; } class Child extends Parent { public static int publicStaticField; private static int privateStaticField; } public class ReflectionExample { public static void main(String[] args) { Class<Child> childClass = Child.class; System.out.println("getFields() - Public Fields:"); Field[] publicFields = childClass.getFields(); for (Field field : publicFields) { System.out.println(field.getName()); } System.out.println("\ngetDeclaredFields() - All Fields:"); Field[] declaredFields = childClass.getDeclaredFields(); for (Field field : declaredFields) { System.out.println(field.getName()); } } } In this example:
getFields() retrieves only the publicField and publicStaticField because they are the only public fields. It doesn't include private fields or fields from the superclass.
getDeclaredFields() retrieves all fields, including publicField, privateField, publicStaticField, and privateStaticField. It includes both accessible and non-accessible fields declared in the class.
Keep in mind that when using reflection, you may need to use setAccessible(true) on non-public fields to access and modify their values if necessary. However, it's generally recommended to respect encapsulation and access fields using appropriate getter and setter methods when possible.
border-box celery-task cucumber active-directory grand-central-dispatch excel scripting kendo-ui-angular2 vpn android-query