gpt4 book ai didi

java - 动态获取 Java 对象字段的值(通过反射)

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:35:01 25 4
gpt4 key购买 nike

我得到类中各个字段的名称,如下所示:

Field[] f = MyClass.class.getDeclaredFields();
Sring str = f[0].toString();
MyClass cl = new MyClass();

现在我想从对象 cl 动态访问(公共(public))字段 str。我该怎么做?

最佳答案

使用 Field.get像这样的方法(对于第 0 个字段):

Object x = f[0].get(cl);

要弄清楚 str 字段有哪个索引,你可以这样做

int strIndex = 0;
while (!f[strIndex].getName().equals("str"))
strIndex++;

这里有一个完整的例子来说明它:

import java.lang.reflect.Field;

class MyClass {
String f1;
String str;
String f2;
}

class Test {
public static void main(String[] args) throws Exception {
Field[] f = MyClass.class.getDeclaredFields();
MyClass cl = new MyClass();
cl.str = "hello world";

int strIndex = 0;
while (!f[strIndex].getName().equals("str"))
strIndex++;

System.out.println(f[strIndex].get(cl));

}
}

输出:

hello world

关于java - 动态获取 Java 对象字段的值(通过反射),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6478302/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com