仅检索在Java类中声明的静态字段 [英] Retrieve only static fields declared in Java class

查看:68
本文介绍了仅检索在Java类中声明的静态字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:

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

是否可以使用反射来获取静态字段列表?我知道我可以使用 Test.class.getDeclaredFields()获取所有字段的数组。但似乎没有办法确定 Field 实例是否代表静态字段。

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.

推荐答案

你可以这样做:

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

这篇关于仅检索在Java类中声明的静态字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆