Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top