1

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

Community
  • 1
  • 1
brain storm
  • 30,124
  • 69
  • 225
  • 393

3 Answers3

3

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.

David Conrad
  • 15,432
  • 2
  • 42
  • 54
  • that did not help. did you try it? – brain storm Mar 03 '14 at 21:14
  • Yes, I tried it. It works. You still need the other parts of the code, such as `setAccessible(true)`. – David Conrad Mar 03 '14 at 21:17
  • I tried it. It works. You need to put the "new" line at the top of main, and replace the "int y=" line with the one provided. – Ted Bigham Mar 03 '14 at 21:18
  • It doesn't matter where the "new" line is, as long as it is before the "int y=" line. – David Conrad Mar 03 '14 at 21:23
  • @DavidConrad: please see my edit above. I tried as you suggested but it fails. if my code above is wrong, please paste what you tried. – brain storm Mar 03 '14 at 21:23
  • I just copied the code from your edit, and it works for me with Java 1.7.0_40. What error are you getting? Is it possible you have some other A.class on your classpath? – David Conrad Mar 03 '14 at 21:29
  • 1
    You could also use `A.class` or `new A().getClass()` instead of `Class.forName("A")` to make sure you are getting the right class. What line is the exception being thrown on? – David Conrad Mar 03 '14 at 21:35
0

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());
helderdarocha
  • 23,209
  • 4
  • 50
  • 65
0

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

Ashot Karakhanyan
  • 2,804
  • 3
  • 23
  • 28