如何通过反射访问抽象父类中的实例字段?
例如,StringBuilder
继承自抽象类AbstractStringBuilder
。据我了解,StringBuilder
本身没有字段(serialVersionUID
除外)。相反,它的状态由 AbstractStringBuilder
中的字段表示,并通过在其重写的方法的实现中调用 super
进行操作。
有没有办法通过反射来获取与 StringBuilder 的特定实例关联的
AbstractStringBuilder
中声明的名为 value
的私有 char
数组?这是我最接近的。
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( ));
}
}
这让我得到了一个包含 16 个空字符的数组。请注意,我正在寻找涉及反射的解决方案,因为我需要一种不限于 StringBuilder
的通用技术。有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的问题是你正在检查一个新的 StringBuilder...所以它当然是空的(默认大小是 16 个字符)。您需要传入
foo
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
Apache Commons BeanUtils 库可能值得一看。以下是其 API Javadocs 的链接。该库包含许多高级方法,使 Reflection 更易于使用。
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.