java反射嵌套对象设置私有(private)字段

标签 java reflection

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

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

问题是 f 是一个 Field 而不是 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");

关于java反射嵌套对象设置私有(private)字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40110327/

相关文章:

c# - 如何使用反射来确定属性上是否存在属性?

java - 将数据从Controller传递到jsp

java - 垃圾收集YGCT和垃圾收集时间持续上升

Java编译器告诉我我还没有初始化变量 "interest"或 "pmt"

java - 迭代字符串。搜索特殊字符。使用正则表达式

c - 在 C 中在运行时获取变量的类型

java - 如何在Java中提供本地PDF文件的下载?

c# - 这是.Net 反射中的错误吗?

java - 任何以注释方式在没有Spring的情况下读取属性文件的API

Android 反射困惑