开发者

Get value of final field of a static class using reflection

开发者 https://www.devze.com 2023-03-14 16:55 出处:网络
I have following class structure: private static class MyStaticClass { public final String name; public final String photoUri;

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


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消