Take the 2-minute tour ×

I have following class structure:

       private static class MyStaticClass {  
          public final String name;  
          public final String photoUri; 
          private MyStaticClass(String pName, String pPhotoUri) {
               this.name = pName;
               this.photoUri = pPhotoUri;

          public static MyStaticClass getNewMyStaticClass(String pName) {
              return new MyStaticClass(pName, null);

Now when I want to read the value of "name" and "photoUri" fields, it gives me "Object is not an instance of class". Following is the code:

void printValues() {
    try {
        Class cls = Class.forName("my.pkg.name.TestClass$MyStaticClass");
        for(Field field: cls.getDeclaredFields()) {
            System.out.println("Field name: " + field.getName());
            System.out.println("Field value: " + field.get(cls));
    } catch (Throwable e) {

I also tried to pass "null" at field.get(null) to read the value but it gives null pointer exception.

Please help me, how can I read the value of the field "name" and "photoUri"?

share|improve this question
Please add the code of the outer class TestClass for clarity sake. –  Laurent Pireyn Jun 21 '11 at 18:57
add comment

3 Answers

up vote 0 down vote accepted

A static nested class is an actual class except that its not top-level. Since you are trying to look at member variables of this class, you actually need an instantiated object of that class to do this.

share|improve this answer
add comment

Your fields are not static, you should specify an instance when calling field.get().

Calling it like this does work:

field.get(new MyStaticClass("name", "photoUri"))
share|improve this answer
He will most likely need to also call field.setAccessible(true) –  Reverend Gonzo Jun 21 '11 at 19:14
Don't think so, fields are declared public. –  wjans Jun 21 '11 at 19:15
Ah...good point. I didn't see that. –  Reverend Gonzo Jun 21 '11 at 19:31
add comment

Expression field.get(cls) will actually attempt to extract field's value from the cls, but field belongs MyStaticClass, not Class (since you are iterating through all fields declared in MyStaticClass). This expression will throw an IllegalArgumentException.

Use field.get(o), where o is an instance of MyStaticClass or a subclass thereof.

share|improve this answer
add comment

Your Answer


