문제

I read this post and followed the guidelines there. but that did not help; I get NoSuchFieldException when the field exists. The sample code is below:

Here is my 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);
    }
}

EDIT: per answer below, I tried this:

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

but the error is same

도움이 되었습니까?

해결책

The Object parameter of Field#getInt must be an instance of class A.

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

Since the name and number fields are not static, you cannot get them from the class; you must get them from a particular instance of the class.

다른 팁

If your code is exactly as above, there shouldn't be any NoSuchFieldException. But there will be probably an IllegalAccessException. You should pass an instance of the class to getInt():

int y = testnum.getInt(cls.newInstance());

Use

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

Instead of

int y = testnum.getInt(testnum);

Because the method wants as a parameter the object (the object of class A, not a Field class which you are using)to extract

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top