Retrieve only static fields declared in Java class

JavaReflectionStaticField

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

I stumbled across this question by accident and felt it needed a Java 8 update using streams:

public static List<Field> getStatics(Class<?> clazz) {
	List<Field> result;

	result = Arrays.stream(clazz.getDeclaredFields())
			// filter out the non-static fields
			.filter(f -> Modifier.isStatic(f.getModifiers()))
			// collect to list
			.collect(toList());

	return result;
}

Obviously, that sample is a bit embelished for readability. In actually, you would likely write it like this:

public static List<Field> getStatics(Class<?> clazz) {
	return Arrays.stream(clazz.getDeclaredFields()).filter(f ->
        Modifier.isStatic(f.getModifiers())).collect(toList());
}

Solution 3 - Java

Thats Simple , you can use Modifier to check if a field is static or not. Here is a sample code for that kind of task.

public static void printModifiers(Object o) {
    Class c = o.getClass();
    int m = c.getModifiers();
    if (Modifier.isPublic(m))
        System.out.println ("public");
    if (Modifier.isAbstract(m))
        System.out.println ("abstract");
    if (Modifier.isFinal(m))
        System.out.println ("final");
    if(Modifier.isStatic(m))
        System.out.println("static");
}

Solution 4 - Java

If you can add open-source dependencies to your project you can also use FieldUtils.readDeclaredStaticField(Test.class,"a")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndersView Question on Stackoverflow
Solution 1 - JavaAbhinav SarkarView Answer on Stackoverflow
Solution 2 - JavaTorqueView Answer on Stackoverflow
Solution 3 - JavaSalman SalehView Answer on Stackoverflow
Solution 4 - JavapaskosView Answer on Stackoverflow