Java-通过反射访问非静态属性
我想用字符串名获取我的类属性。Java-通过反射访问非静态属性,java,Java,我想用字符串名获取我的类属性。 我有这样的代码 class Test { public String simple = "hello"; public void getSetting() { try { Test c = new Test(); Class cls = this.getClass(); Field field = cls.getField("simpl
我有这样的代码
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
}
}
}
这段代码有一个错误,因为我的属性是非静态的,当我将属性更改为静态时,工作正常,如何通过反射获取非静态属性?下面是一个关于如何通过反射获取实例
字段的自含示例
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();
}
}
}
该字段必须是静态的,或者属于可以通过反射获取的实例。在测试类中创建一个方法来完成这项工作。实例化该类并调用该方法。顺便问一下,什么是public main()
?“public main()”这不应该编译,您是指public static void main()还是指public Test(),那么,您可以共享您的代码吗?什么?您不使用c
。也永远不要忽略例外情况
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();
}
}
}
try
{
Test c = new Test();
Class cls = c.getClass(); //Change this.getClass to c.getClass()
Field field = cls.getField("simple");;
}