How can I access an instance field in an abstract parent class via reflection?

允我心安 提交于 2020-01-13 05:46:07

问题


So, for example, StringBuilder inherits from the abstract class AbstractStringBuilder. As I understand it, StringBuilder has no fields itself (except for serialVersionUID). Rather, its state is represented by the fields in AbstractStringBuilder and manipulated by calling super in the implementations of the methods it overrides.

Is there a way via reflection to get the private char array named value declared in AbstractStringBuilder that is associated with a particular instance of StringBuilder? This is the closest I got.

import java.lang.reflect.Field;
import java.util.Arrays;

public class Test
{
   public static void main(String[ ] args) throws Exception
   {
      StringBuilder foo = new StringBuilder("xyzzy");
      Field bar = foo.getClass( ).getSuperclass( ).getDeclaredField("value");
      bar.setAccessible(true);
      char[ ] baz = (char[ ])bar.get(new StringBuilder( ));
   }
}

That gets me an array of sixteen null characters. Note that I'm looking for solutions involving reflection, since I need a general technique that isn't limited to StringBuilder. Any ideas?


回答1:


char[ ] baz = (char[ ])bar.get(new StringBuilder( ));

Your problem is that you're inspecting a new StringBuilder... so of course it's empty (and 16 chars is the default size). You need to pass in foo




回答2:


It might be worth looking in the Apache Commons BeanUtils library. Here is the link to their API Javadocs. The library contains lots of high-level methods that make Reflection easier to use.



来源:https://stackoverflow.com/questions/4361714/how-can-i-access-an-instance-field-in-an-abstract-parent-class-via-reflection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!