【问题标题】:Public field from String - How can you get a public field vis its name(string) [duplicate]字符串中的公共字段-如何根据其名称(字符串)获取公共字段[重复]
【发布时间】:2017-05-08 18:39:40
【问题描述】:

所以在课堂上(ImportantClass123)我有这个:

public AnotherImportantClass aReallyImportantClass;

如何退货

AnotherImportantClass

通过了解它的字段名称:

aReallyImportantClass

有点像

ImportantClass123.getFieldWithName("aReallyImportantClass");

?

如何编写 getFieldWithName?它的返回类型是什么?上课?

【问题讨论】:

标签: java class field public


【解决方案1】:

您可以使用反射来获取该信息。方法Class.getField(String) 为名称给出的公共字段返回一个Field 对象。 Field 对象有一个方法getType(),它将为您提供该字段的类型:

public class Snippet {
    public Integer x;

    public static void main(String[] args) throws Exception {
        Field x = Snippet.class.getField("x");
        Class<?> type = x.getType();
        System.out.println("Type of field x: " + type);
    }
}

【讨论】:

    猜你喜欢
    • 2011-07-13
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    • 2011-02-15
    • 1970-01-01
    • 2011-11-26
    • 2010-11-04
    • 1970-01-01
    相关资源
    最近更新 更多