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
The problem is that
f
is aField
not aBar
.You need to start with
foo
, extract the value offoo.bar
, and then use that object reference; e.g. something like this