通过反射获取字段
我有一个已包装的对象,因此每当我执行以下操作时;
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我假设 builder.getClass() 返回错误的类。您可能必须查找包装的对象并对其调用
getClass()
,或者 - 如果您可以更改构建器 - 提供一个方法来获取包装对象的类。I assume
builder.getClass()
returns the wrong class. You might have to look up the wrapped object and callgetClass()
on it or - if you can change the builder - provide a method to get the class of the wrapped object.你的意思是改变字段的值?您可以调用
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首先,您可以使用
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 objectbuilder
: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.