Search code examples
javaclassreflectionfieldnosuchfileexception

NoSuchFieldException when trying to retrieve the value of field


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


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.