java中获取字符串的变量值

2 java variables

我希望用户可以告诉我的代码,当某个变量具有某个值时,它应该执行某些操作。我已经编写了一个简单的代码示例,展示了我希望的样子,希望您能够理解它。有没有可能以任何方式创建一个字符串并让Java检查带有相同名称的变量是否等于另一个变量的值。

int turn = 1;
String variable = "turn";
int compareToThisValue = 1;

if (variable.toVariable() == compareToThisValue) {
    System.out.println("Yes it works thank you guys!");
{
Run Code Online (Sandbox Code Playgroud)

Agn*_*bha 6

我想下面的代码可以提供帮助。它使用 java Reflection 来完成工作。如果您有其他要求,可以对此进行调整。

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)