Retrieve only static fields declared in Java class

Anders picture Anders · Aug 6, 2010 · Viewed 83.8k times · Source

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.

Answer

Abhinav Sarkar picture Abhinav Sarkar · Aug 6, 2010

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);
    }
}