Java - 使用反射访问非静态属性

时间:2014-08-21 08:05:54

标签: java

我想用字符串名称获取我的类属性 我有这样的代码

class Test
{
    public String simple = "hello";

    public void getSetting()
    {
        try
        {
            Test c = new Test();
            Class cls = this.getClass();
            Field field = cls.getField("simple");;
        }
        catch(Exception e)
        {
            // error
        }

    }
}

我的代码出错了,因为我的属性是非静态的,当我将属性更改为静态时,它的工作正常,我怎样才能获得带反射的非静态属性?

2 个答案:

答案 0 :(得分:3)

这是一个关于如何通过反射获取实例Field的自包含示例。

public class Main {
    // the instance field
    String simple = "foo";
    // some static main method
    public static void main(String[] args) throws Exception {
        // initializing the class as we're accessing an instance method
        new Main().reflect();
    }

    public void reflect() {
        Class<?> c = this.getClass();
        try {
            // using getDeclaredField for package-protected / private fields
            Field field = c.getDeclaredField("simple");
            // printing out field's value for this instance
            System.out.println(field.get(this));
        }
        // TODO handle better
        catch (IllegalAccessException iae) {
            iae.printStackTrace();
        }
        catch (NoSuchFieldException n) {
            n.printStackTrace();
        }
    }
}

<强>输出

foo

答案 1 :(得分:0)

try
{
    Test c = new Test();
    Class cls = c.getClass();              //Change this.getClass to c.getClass()
    Field field = cls.getField("simple");;
}

Field必须是静态的或属于可以通过反射获得的实例。