sebastian
sebastian

Reputation: 55

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();

Upvotes: 0

Views: 202

Answers (2)

eparvan
eparvan

Reputation: 1729

If you are using Java 8, you may modify the getValue method in the following way:

  public <T> T getValue(Function<Integer, T> parser) {
      return Optional.of(value).map(parser).get();
  }

Example:

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

  //getting values

  Long longValue = $t2.getValue(Integer::longValue);
  Double doubleValue = $t2.getValue(Integer::doubleValue);
  String stringValue = $t2.getValue(i -> i.toString());
  Integer integerValue = $t2.getValue(Integer::valueOf);
  System.out.print("long: " + longValue + ", double: " + doubleValue + ", string: " + stringValue + ", integer: " + integerValue);

Output: long: 20, double: 20.0, string: 20, integer: 20

Upvotes: 0

GhostCat
GhostCat

Reputation: 140467

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.

Upvotes: 1

Related Questions