java reflection nested object set private field

2019-09-18 02:40发布

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
}

}

the exception i get is:

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

1条回答
相关推荐>>
2楼-- · 2019-09-18 03:07
f2.set(f, "hello world");

The problem is that f is a Field not a Bar.

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");
查看更多
登录 后发表回答