Java:如何通过存储在变量中的名称访问类的字段?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2127197/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 03:50:56  来源:igfitidea点击:

Java: How can I access a class's field by a name stored in a variable?

javaclassfield

提问by ufk

How can I set or get a field in a class whose name is dynamic and stored in a string variable?

如何在名称为动态并存储在字符串变量中的类中设置或获取字段?

public class Test {

    public String a1;
    public String a2;  

    public Test(String key) {
        this.key = 'found';  <--- error
    } 

}

采纳答案by Jon Skeet

You have to use reflection:

你必须使用反射:

Here's an example which deals with the simple case of a public field. A nicer alternative would be to use properties, if possible.

这是一个处理公共字段简单情况的示例。如果可能,更好的选择是使用属性。

import java.lang.reflect.Field;

class DataObject
{
    // I don't like public fields; this is *solely*
    // to make it easier to demonstrate
    public String foo;
}

public class Test
{
    public static void main(String[] args)
        // Declaring that a method throws Exception is
        // likewise usually a bad idea; consider the
        // various failure cases carefully
        throws Exception
    {
        Field field = DataObject.class.getField("foo");
        DataObject o = new DataObject();
        field.set(o, "new value");
        System.out.println(o.foo);
    }
}

回答by JITHIN_PATHROSE

Class<?> actualClass=actual.getClass();

Field f=actualClass.getDeclaredField("name");

The above code would suffice .

上面的代码就足够了。

object.class.getField("foo");

Unfortunately the above code didn't work for me , since the class had empty field array.

不幸的是,上面的代码对我不起作用,因为该类有空的字段数组。