我读了这的帖子,跟着guidelines去了那里。但是这并没有帮助;当字段存在时,我得到了NoSuchFieldException。示例code如下:
这是我的代码:
class A{
private String name="sairam";
private int number=100;
}
public class Testing {
public static void main(String[] args) throws Exception {
Class cls = Class.forName("A");
Field testnum=cls.getDeclaredField("number");
testnum.setAccessible(true);
int y = testnum.getInt(testnum);
System.out.println(y);
}
}编辑:根据下面的回答,我尝试了以下方法:
Class cls = Class.forName("A");
Field testnum=cls.getDeclaredField("number");
testnum.setAccessible(true);
A a = new A();
int y = testnum.getInt(a);
System.out.println(y);但是错误是一样的
发布于 2014-03-03 21:11:20
Object参数Field#getInt必须是class A的实例。
A a = new A();
int y = testnum.getInt(a);由于name和number字段不是静态的,所以不能从类中获取它们;必须从类的特定实例中获取它们。
发布于 2014-03-03 21:17:58
如果您的代码与上面完全相同,那么就不应该有任何NoSuchFieldException。但可能会有一个IllegalAccessException。您应该将类的一个实例传递给getInt()
int y = testnum.getInt(cls.newInstance());发布于 2014-03-03 21:31:33
使用
int y = testnum.getInt(new A());而不是
int y = testnum.getInt(testnum);因为该方法需要对象(类A的对象,而不是您使用的Field类的对象)作为参数进行提取。
https://stackoverflow.com/questions/22157312
复制相似问题