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?