简体   繁体   English

Java反射嵌套对象设置私有字段

[英]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. 我正在尝试使用反射设置一个私有的嵌套字段(本质上是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
}

} }

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 . 问题是f是一个Field而不是Bar

You need to start with foo , extract the value of foo.bar , and then use that object reference; 您需要从foo开始,提取foo.bar ,然后使用该对象引用。 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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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