java反射嵌套对象集私有字段

java反射嵌套对象集私有字段,java,reflection,Java,Reflection,我正在尝试使用反射设置一个私有嵌套字段(基本上是Bar.name),但我遇到了一个无法理解的异常 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 f

我正在尝试使用反射设置一个私有嵌套字段(基本上是Bar.name),但我遇到了一个无法理解的异常

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
}
问题是
f
字段
而不是

您需要从
foo
开始,提取
foo.bar
的值,然后使用该对象引用;e、 像这样的

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");
问题是
f
字段
而不是

您需要从
foo
开始,提取
foo.bar
的值,然后使用该对象引用;e、 像这样的

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");
f2.set(f.get(foo),“hello world”)?您试图在存储在
Foo.bar
中的实例上设置它,而不是在类上设置它。
f2.set(f.get(Foo),“hello world”)?您试图在存储在
Foo.bar
中的实例上设置它,而不是在类上。
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");