java反射嵌套对象设置私有字段 [英] java reflection nested object set private field
本文介绍了java反射嵌套对象设置私有字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用反射设置一个私有嵌套字段(基本上是 Bar.name),但我遇到了一个我无法弄清楚的异常.
i'm trying set a private nested field (essentially Bar.name) using reflection, but i'm getting an exception i can't figure out.
import java.lang.reflect.Field;
public class Test {
public static void main(String[] args) throws Exception {
Foo foo = new Foo();
Field f = foo.getClass().getDeclaredField("bar");
Field f2 = f.getType().getDeclaredField("name");
f2.setAccessible(true);
f2.set(f, "hello world"); // <-- error here!! what should the first parameter be?
}
public static class Foo {
private Bar bar;
}
public class Bar {
private String name = "test"; // <-- trying to change this value via reflection
}
}
我得到的例外是:
Exception in thread "main" java.lang.IllegalArgumentException: Can not set java.lang.String field com.lmco.f35.decoder.Test$Bar.name to java.lang.reflect.Field
推荐答案
f2.set(f, "hello world");
问题在于 f
是 Field
而不是 Bar
.
The problem is that f
is a Field
not a Bar
.
你需要从foo
开始,提取foo.bar
的value,然后使用那个对象引用;例如像这样
You need to start with foo
, extract the value of foo.bar
, and then use that object reference; e.g. something like this
Foo foo = new Foo();
Field f = foo.getClass().getDeclaredField("bar");
f.setAccessible(true);
Bar bar = (Bar) f.get(foo);
// or 'Object bar = f.get(foo);'
Field f2 = f.getType().getDeclaredField("name");
f2.setAccessible(true);
f2.set(bar, "hello world");
这篇关于java反射嵌套对象设置私有字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文