How can I access an instance field in an abstract parent class via reflection?
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( ).getDeclar开发者_Go百科edField("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?
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
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.
精彩评论