Java 尝试检索字段值时出现NoSuchFieldException

Java 尝试检索字段值时出现NoSuchFieldException,java,class,reflection,field,nosuchfileexception,Java,Class,Reflection,Field,Nosuchfileexception,我读了这篇文章,并遵循了那里的指南。但这没有帮助;当字段存在时,我得到NoSuchFieldException。示例代码如下所示: 这是我的密码: class A{ private String name="sairam"; private int number=100; } public class Testing { public static void main(String[] args) throws Exception { Class cls = C

我读了这篇文章,并遵循了那里的
指南。但这没有帮助;当字段存在时,我得到
NoSuchFieldException
。示例代码如下所示:

这是我的密码:

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);

但是错误是相同的

对象
参数必须是
A类
的实例

A a = new A();
int y = testnum.getInt(a);

由于
name
number
字段不是静态的,因此无法从类中获取它们;您必须从类的特定实例中获取它们。

如果您的代码与上面的代码完全相同,则不应存在任何
NoSuchFieldException
。但是可能会出现一个
非法访问异常
。应该将类的实例传递给
getInt()

使用

而不是

int y = testnum.getInt(testnum);

因为该方法希望将对象(类
a
的对象,而不是您正在使用的
字段
类)作为参数来提取没有帮助的

。你试过了吗?是的,我试过了。它起作用了。您仍然需要代码的其他部分,例如
setAccessible(true)
。我试过了。它起作用了。您需要将“new”行放在main的顶部,并用提供的行替换“int y=”行。只要“new”行在“int y=”行之前,“new”行在哪里并不重要。您还可以使用
A.class
new A().getClass()
而不是
class.forName(“A”)
以确保您获得了正确的课程。在哪一行抛出异常?
 int y = testnum.getInt(new A());
int y = testnum.getInt(testnum);