So, for example, StringBuilder inherited from the abstract class AbstractStringBuilder . As far as I understand, StringBuilder has no fields (except serialVersionUID ). Rather, its state is represented by fields in AbstractStringBuilder and is controlled by a call to super in the implementations of the methods that it overrides.
Is there a way through reflection to get a private char array named value declared in AbstractStringBuilder that is associated with a specific StringBuilder instance? 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( )); } }
This gives me an array of sixteen null characters. Note that I'm looking for solutions that include reflection, since I need a generic method that is not limited to StringBuilder . Any ideas?
source share