I have the following class:
public class Test { public static int a = 0; public int b = 1; }
Is it possible to use reflection to get a list of the static fields only? I'm aware I can get an array of all the fields with Test.class.getDeclaredFields()
. But it seems there's no way to determine if a Field
instance represents a static field or not.
Static public fields are added to the class constructor at the time of class evaluation using Object. defineProperty() . The static fields and methods can be accessed from the class itself.
The list of all declared fields can be obtained using the java. lang. Class. getDeclaredFields() method as it returns an array of field objects.
3. The static Fields (or Class Variables) In Java, when we declare a field static, exactly a single copy of that field is created and shared among all instances of that class. It doesn't matter how many times we initialize a class. There will always be only one copy of static field belonging to it.
Third, the Java field can be declared static . In Java, static fields belongs to the class, not instances of the class. Thus, all instances of any class will access the same static field variable. A non-static field value can be different for every object (instance) of a class.
You can do it like this:
Field[] declaredFields = Test.class.getDeclaredFields(); List<Field> staticFields = new ArrayList<Field>(); for (Field field : declaredFields) { if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) { staticFields.add(field); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With