A
A
Alexander2015-03-17 14:31:05
Java
Alexander, 2015-03-17 14:31:05

How to set the value of a variable with a dynamic name in java?

there is this code:

double var1;
String var2;
String var3

public bool setValue(String key, String value) {
        /* ??? */
}

can i somehow by calling the function setValue("var1", "0"); write values ​​to the var1 variable without using constructs like if(key == "var1") var = value; and switch {...} ?
Those. You need to check if the variable is declared in the class. If yes, then determine its type, convert the string to this type, and write the value. If not, return false.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Pronin, 2015-03-17
@wxmaper

look at Reflection.

public bool setValue(String key, String value) {
        try {
            declaredField = this.getClass().getDeclaredField("var");
            declaredField.set(this,value);
        } catch (NoSuchFieldException e) {
            return false
        }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question