如何通过反射访问抽象父类中的实例字段? [英] How can I access an instance field in an abstract parent class via reflection?

查看:91
本文介绍了如何通过反射访问抽象父类中的实例字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,例如, StringBuilder 继承自抽象类 AbstractStringBuilder 。据我了解, StringBuilder 本身没有字段( serialVersionUID 除外)。相反,它的状态由 AbstractStringBuilder 中的字段表示,并通过在它覆盖的方法的实现中调用 super 进行操作。 。

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.

有没有办法通过反射来获取名为的私有 char 数组 AbstractStringBuilder 中声明与 StringBuilder 的特定实例相关联?这是我最接近的。

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( ));
   }
}

这会得到一个由十六个空字符组成的数组。请注意,我正在寻找涉及反射的解决方案,因为我需要一种通用技术,不仅限于 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( ));

你的问题是你正在检查一个新的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

这篇关于如何通过反射访问抽象父类中的实例字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆