gpt4 book ai didi

Java,获取一个类的所有变量值

转载 作者:行者123 更新时间:2023-12-01 13:43:05 25 4
gpt4 key购买 nike

所以我有一个名为 Test 的类:

public class Test{
protected String name = "boy";
protected String mainAttack = "one";
protected String secAttack = "two";
protected String mainType"three";
protected String typeSpeak = "no spoken word in super class";

//Somehow put all the class variables in an Array of some sort
String[] allStrings = ??(all class' strings);
//(and if you feel challenged, put in ArrayList without type declared.
//So I could put in, not only Strings, but also ints etc.)

public void Tester(){
//Somehow loop through array(list) and print values (for-loop?)
}
}

如您所见,我想自动将所有类变量放入 Array 或 ArrayList (或类似的东西)中。接下来我希望能够循环遍历数组并打印/获取值。最好使用增强的 for 循环。

最佳答案

正如其他人所说,不要这样做。但这是这样的:

Class<?> cl = this.getClass();
List<Object> allObjects = new ArrayList<Object>();
for (java.lang.reflect.Field f: cl.getDeclaredFields())
{
f.setAccessible(true);
try
{
Object o = f.get(this);
allObjects.add(o);
}
catch (Exception e)
{
...
}
}
for (Object o: allObjects)
System.out.println(o);

关于Java,获取一个类的所有变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20545189/

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