通过反射获取字段

发布于 2024-12-18 19:04:25 字数 338 浏览 3 评论 0原文

我有一个已包装的对象,因此每当我执行以下操作时;

        Field[] fields = builder.getClass().getDeclaredFields(); 

        String s = "";
        for(Field f : fields)
        {
            s+= " " + f.getName();
        }

我得到的字段不属于我的班级。如果我想修改一个被包装的字段,是否可以通过反射来做到这一点?

谢谢

编辑:是的,我在展开的对象上调用了它。抱歉 - 这是漫长的一天:/

I have an object that has been wrapped so whenever i do the following;

        Field[] fields = builder.getClass().getDeclaredFields(); 

        String s = "";
        for(Field f : fields)
        {
            s+= " " + f.getName();
        }

I get fields that aren't in my class. If i want to modify a field that ahs been wrapped, is it possible to do so via reflection?

Thanks

edit: yes i called it on the unwrapped object. Sorry - its been a long day :/

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

べ繥欢鉨o。 2024-12-25 19:04:25

我假设 builder.getClass() 返回错误的类。您可能必须查找包装的对象并对其调用 getClass() ,或者 - 如果您可以更改构建器 - 提供一个方法来获取包装对象的类。

I assume builder.getClass() returns the wrong class. You might have to look up the wrapped object and call getClass() on it or - if you can change the builder - provide a method to get the class of the wrapped object.

月竹挽风 2024-12-25 19:04:25

你的意思是改变字段的值?您可以调用f.set(builder,)。不确定你所说的包裹对象是什么意思,可能是你想在执行反射魔法之前打开它

do you mean change the value of the field? you could call f.set(builder, <value>). not sure what you mean by wrapped object, may be you want to unwrap it before you perform the do the reflection magic

寂寞美少年 2024-12-25 19:04:25

首先,您可以使用 YourClass.getDeclaredFields() 而不是尝试使用对象 builder 访问字段: builder.getClass().getDeclaredFields();

其次,如果您的类被其他类包装,则意味着外部对象保存对内部对象(希望是您的)的引用。因此,您必须发现外部对象以查看它具有哪些字段以及哪个字段保存对内部对象的引用。然后调用inner =outer.getField("theFiledName").getValue(builder)

现在您可以完全按照您在代码片段中尝试的方式使用 inner

First you can use YourClass.getDeclaredFields() instead of attempting to access the fields using object builder: builder.getClass().getDeclaredFields();

Second, if your class is wrapped by other class it means that outer object holds reference to inner one (hopefully yours). So you have to discover the outer object to see which fields does it have and which field holds reference to your inner object. Then call inner =outer.getField("theFiledName").getValue(builder).

Now you can use inner exactly as you tried in your code snippet.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文