gpt4 book ai didi

java - 当只有字符串形式的变量名称时获取变量的值

转载 作者:行者123 更新时间:2023-12-01 16:33:32 24 4
gpt4 key购买 nike

int text01=2012;
String entrance= "text01";

如何通过字符串“entrance”获取“text01”的int value(2012)

最佳答案

如果你知道类是什么,你可以使用反射:

public class Test
{
int text01 = 2012;
}

在其他地方,您可以通过以下方式获取该字段的值:

String entrance = "text01";
Test t = new Test();

Field f = t.getClass().getDeclaredField(entrance);
System.out.println("value = "+f.getInt(t));

// you can even change the value:
t.text01 = 2013;
System.out.println("value = "+f.getInt(t));

这将打印出 2012,然后打印出 2013

关于java - 当只有字符串形式的变量名称时获取变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11876475/

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