Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic variable names Java

Tags:

java

How will I be able to retrieve the value of a variable which has a dynamic name

For Example I have list of constants

public class Constant{
    public static final String S_R = "Standard(240)";
    public static final String S_W = "Standard(180)";
    public static final String L_R = "Large(360)";
    public static final String L_W = "Large(280)";
}

Based on database I build a variable name

String varName = "S" + "_"  +"R"; // This can be S_R , S_W , L_R or L_W
String varVal = // How do i get value of S_R
like image 459
Pit Digger Avatar asked Apr 27 '11 14:04

Pit Digger


2 Answers

Use a normal HashMap with variable names as strings against their values. Or use a EnumMap with enums as key and your value as values. AFAIK, that's the closest you can get when using Java. Sure, you can mess around with reflection but IMO the map approach is much more logical.

like image 142
Sanjay T. Sharma Avatar answered Nov 02 '22 23:11

Sanjay T. Sharma


You can use a Map<String, String> and locate the value by its key.

Even better, you can have an enum:

public enum Foo {
    S_R("Standard", 240),
    S_W("Standard", 180),...;

    private String type;
    private String duration;

    // constructor and getters
}

And then call Foo.valueOf(name)

(You can also do this via reflection - Constants.class.getField(fieldName) and then call field.get(null) (null for static). But that's not really a good approach.)

like image 39
Bozho Avatar answered Nov 03 '22 01:11

Bozho