【问题标题】:java reflection nested object set private fieldjava反射嵌套对象集私有字段
【发布时间】:2016-10-18 14:00:44
【问题描述】:

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

}

我得到的例外是:

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.get(foo), "hello world");?您正在尝试将其设置在存储在 Foo.bar 中的实例上,而不是类上。

标签: java reflection


【解决方案1】:
f2.set(f, "hello world");

问题在于fField 而不是Bar

你需要从foo开始,提取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");

【讨论】:

    猜你喜欢
    • 2018-02-02
    • 1970-01-01
    • 2011-02-02
    • 1970-01-01
    • 2013-02-25
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    • 2015-07-08
    相关资源
    最近更新 更多