0

I see

MyClass.class.getDeclaredMethods()
MyClass.class.getDeclaredFields()

but how do I get just the non-static or just the static members?

Andrew Cheong
  • 29,362
  • 15
  • 90
  • 145
  • 1
    FYI, it was the first result on Google for "java static field reflection". – Michael Jan 16 '19 at 18:55
  • @Michael - Woops. When I searched with "non-static" instead of "static" and including "getDeclaredMethods", I got totally different results about invoking non-static methods. Sorry. – Andrew Cheong Jan 16 '19 at 19:00

1 Answers1

3

You can use Modifier#isStatic for that, for example:

Field[] fields = Main.class.getDeclaredFields();
for (Field f : fields) {
    if (Modifier.isStatic(f.getModifiers())) {
        System.out.println(f.getName());
    }
}

This will print b if Main is:

public class Main {

    public String a;
    public static String b;


}
Mark
  • 5,089
  • 2
  • 20
  • 31