简体   繁体   中英

java reflection nested object set private field

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
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; eg 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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM