是否可以将 int
变量的名称存储在字符串中,并使用该字符串作为参数来更新 int
?
最佳答案
是的,这叫做reflection .
您对 Field 感兴趣类。
示例:
static class A {
public int x = 0;
}
public static void main(String[] args) throws Exception {
A a = new A();
Field f = A.class.getField("x");
f.set(a, 5);
System.out.println(a.x);
}
请注意,虽然这是可能的 - 除了极少数情况外,不建议使用反射,但它有一些主要缺点(可维护性、安全性、性能......) - 这使得替代方案通常 更好的选择。
关于java - 将 int 变量的名称存储在 String 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13002637/