【问题标题】:How do I get just the non-static (or just the static) fields or methods of a class, via reflection? [duplicate]如何通过反射获得类的非静态(或静态)字段或方法? [复制]
【发布时间】:2019-06-10 22:03:17
【问题描述】:

我明白了

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

但我如何只获取非静态成员或仅获取静态成员?

【问题讨论】:

  • 仅供参考,这是 Google 上“java 静态字段反射”的第一个结果。
  • @Michael - 哎呀。当我使用“非静态”而不是“静态”并包括“getDeclaredMethods”进行搜索时,我得到了关于调用非静态方法的完全不同的结果。对不起。

标签: java reflection


【解决方案1】:

您可以为此使用Modifier#isStatic,例如:

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

如果Main 是:这将打印b

public class Main {

    public String a;
    public static String b;


}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-19
    • 2011-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-11
    相关资源
    最近更新 更多