189

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.

Anders
  • 1,977
  • 2
  • 11
  • 10
  • I am a java newer,I want to know why Java did not put these feature all in Field class like C#,What is the benefit from this design? Thanks. – Allen Apr 22 '15 at 10:59
  • https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#getModifiers-- – OrangeDog Nov 02 '16 at 14:59

4 Answers4

383

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);
    }
}
Ivan Marjanovic
  • 979
  • 1
  • 9
  • 15
Abhinav Sarkar
  • 23,534
  • 11
  • 81
  • 97
19

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());
}
Torque
  • 3,319
  • 2
  • 27
  • 39
  • 6
    "In actually, you would likely write it like this" ... why do you think that "in actuality" that readability is not important? – Michael Jan 16 '19 at 18:58
  • 7
    First off, I don't think mocking someones English on a site like this is appropriate. Aside from that, I do not believe that the comments in the embellished example serve to improve readability to someone even remotely familiar with streams, nor does the useless return variable. I would consider both noise if I encountered them in actual code. With more experience with streams under my belt, i would today opt to keep the original newlines for readability. Nobody is perfect. I aimed to provide both an example that was explicit for new programmers as well as one that was realistic. – Torque Jan 16 '19 at 20:12
  • 7
    I wasn't mocking your English. Your English is good. I don't even understand what you're talking about. And yes, I agree that the comments are superfluous and that the formatting of the first is much better. My point was that you seemed to suggest "embellishing for readability" is bad, when readability is an incredibly important code quality metric. – Michael Jan 16 '19 at 20:38
2

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");
}
Michael
  • 41,989
  • 11
  • 82
  • 128
Salman Saleh
  • 173
  • 2
  • 9
-1

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

paskos
  • 689
  • 8
  • 21