仅检索 Java 类中声明的静态字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3422390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Retrieve only static fields declared in Java class
提问by Anders
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.
是否可以使用反射来仅获取静态字段的列表?我知道我可以使用Test.class.getDeclaredFields()
. 但似乎没有办法确定一个Field
实例是否代表一个静态字段。
采纳答案by Abhinav Sarkar
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);
}
}
回答by paskos
If you can add open-source dependencies to your project you can also use FieldUtils.readDeclaredStaticField(Test.class,"a")
如果您可以将开源依赖项添加到您的项目中,您还可以使用 FieldUtils.readDeclaredStaticField(Test.class,"a")
回答by Salman Saleh
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.
这很简单,您可以使用 Modifier 来检查字段是否是静态的。这是此类任务的示例代码。
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");
}
回答by Torque
I stumbled across this question by accident and felt it needed a Java 8 update using streams:
我偶然发现了这个问题,觉得它需要使用流进行 Java 8 更新:
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());
}