Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve only static fields declared in Java class

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.

like image 561
Anders Avatar asked Aug 06 '10 09:08

Anders


People also ask

How do you access a static field in a class?

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.

How do you find the declared field of a class?

The list of all declared fields can be obtained using the java. lang. Class. getDeclaredFields() method as it returns an array of field objects.

What does it mean if we declare a Java field to be static?

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.

Can fields be static?

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.


1 Answers

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);     } } 
like image 191
Abhinav Sarkar Avatar answered Sep 21 '22 17:09

Abhinav Sarkar