2

I would like it so that a user can tell my code that when a certain variable has a certain value it should do something. I have written a simple code sample of what I would like this to look like and I hope you can make sense of it. Is it in any way possible to make a String and let Java check wheter the variable that carries the same name is equal to the value of another variable.

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

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

1 Answers1

6

I guess the following code can help. It uses java Reflection to get the job done. If you have some other requirements this can be tweaked to do so.

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();
        }
    }
}
Agnibha
  • 613
  • 1
  • 11
  • 20