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

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?

+2
source share
2 answers
 char[ ] baz = (char[ ])bar.get(new StringBuilder( )); 

Your problem is that you are checking out a new StringBuilder ... so of course it is empty (and 16 characters is the default size). You have to go foo

+7
source

It might be worth a look at the Apache Commons BeanUtils library. Here is a link to their Javadocs API . The library contains many high-level methods that facilitate the use of Reflection.

0
source

Source: https://habr.com/ru/post/1437863/


All Articles