1

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) { e.printStackTrace(); } } 

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"?

1
  • Please add the code of the outer class TestClass for clarity sake. Commented Jun 21, 2011 at 18:57

3 Answers 3

2

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")) 
Sign up to request clarification or add additional context in comments.

2 Comments

He will most likely need to also call field.setAccessible(true)
Don't think so, fields are declared public.
0

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.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.