sebastian sebastian - 1 month ago 8
Java Question

How get the value from a Object of class through a String?

I have this class

public class Register{
String name;
int value;
int lockedValue = 0;

Registro(String name){ this.name = name; }

public int getValue(){ return value; }
// rest of get and set methods
}


and the main class

public class Simulator{

static Register $t0, $t1, $t2;

public static void main(String[] args) throws IOException {

$t1 = new Register("$t1");
$t1.setValue(15);
$t2 = new Register("$t2");
$t2.setValue(20);


// here i can get values by $t1.getValue()
}

}


I can get the value with a
String
?, like as:

String nameRegister = "$t1";
int fetchValue = nameRegister.getValue();

Answer

It seems that you want to "identify" objects by some string based name. If so, the appropriate data structure in Java is a Map. In your case, you would need something like:

Map<String, Integer> registry = new HashMap<>();
registry.put("t1", 15);
registry.put("t2", 20);

And later you can query this using

Integer value = registry.get("t1");

If you want to store "arbitrary" values, you can/have to use a Map<String, ? extends Object> though. But that isn't exactly a good approach in the first place; as you loose all the compile-time checking that generics would give you.

Comments