gpt4 book ai didi

java - 在 Java 中创建字段数组

转载 作者:行者123 更新时间:2023-11-29 05:15:44 26 4
gpt4 key购买 nike

我正在尝试实现一个程序,该程序将从某个类的字段中创建一个数组然后访问每个字段

我有以下类(class):

public class Example {

public int[] a = {1,2,3};
public int[] b = {1,1,1};
public int[] c = {2,2,2};
}

在不同的类中,我想访问所有这些字段并将它们放入数组“testArray”

import java.lang.reflect.Field;
public class Test {

Example t = new Example();
Field[] testArray = t.getClass().getFields();

for (Field elem: testArray) {
// access the fields
}

}

如何通过这种方式访问​​字段?

注意:由于某些原因,这给了我一个错误,标记“;”上的语法错误,{ expected after this token

最佳答案

你就快完成了:一旦你得到一个字段数组,对每个字段调用 get,传递你希望从中获取属性的对象的实例(在这种情况下,这将是 t):

Object[] fieldsOfT = new Object[testArray.length];
int i = 0;
for (Field f : testArray) {
fieldsOfT[i++] = f.get(t);
}
for (Object v : fieldsOfT) {
System.out.println(v);
}

Demo.

当然这不会打印出对象的漂亮表示,因为 int[] 数组不提供有意义的 toString,但是您拥有作为对象的值,因此您可以转换它,并根据需要打印值。

关于java - 在 Java 中创建字段数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26621995/

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