Retrieve only static fields declared in Java class

后端 未结 4 1221

I have the following class:

public class Test {
    public static int a = 0;
    public int b = 1;
}

Is it possible to use reflection to ge

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-30 00:01

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

    public static List getStatics(Class clazz) {
        List 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 getStatics(Class clazz) {
        return Arrays.stream(clazz.getDeclaredFields()).filter(f ->
            Modifier.isStatic(f.getModifiers())).collect(toList());
    }
    

提交回复
热议问题