繁体   English   中英

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

[英]Java - Access to non-static properties with reflection

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

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
        }

    }
}

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

这是一个关于如何通过反射获取实例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
try
{
    Test c = new Test();
    Class cls = c.getClass();              //Change this.getClass to c.getClass()
    Field field = cls.getField("simple");;
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM