我希望用户可以告诉我的代码,当某个变量具有某个值时,它应该执行某些操作。我已经写了一个简单的代码示例,我希望它看起来像,我希望你能理解它。是否可以以任何方式创建一个字符串并让 Java 检查带有相同名称的变量是否等于另一个变量的值。
int turn = 1;
String variable = "turn";
int compareToThisValue = 1;
if (variable.toVariable() == compareToThisValue) {
System.out.println("Yes it works thank you guys!");
{
我想以下代码可以提供帮助。它使用 Java 反射来完成工作。如果您有其他一些要求,可以对此进行调整。
import java.lang.reflect.*;
class Test {
int turn = 1;
boolean checkValueVariable(String variableName, int value) throws Exception {
Field[] fields = this.getClass().getDeclaredFields();
for (Field field : fields) {
if (field.getName().equals(variableName))
return field.getInt(this) == value;
}
return false;
}
public static void main(String... args) {
Test test = new Test();
String variableName = "turn";
int variableValue = 1;
try {
System.out.println(test.checkValueVariable(variableName, variableValue));
} catch (Exception e) {
e.printStackTrace();
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句