5

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
David Brossard
  • 13,584
  • 6
  • 55
  • 88
Pit Digger
  • 9,618
  • 23
  • 78
  • 122
  • 5
    You can't do that and don't want to do that. You want a `Map` with "S_R", "S_W", ... as keys and the corresponding values. – Joachim Sauer Apr 27 '11 at 14:40

3 Answers3

11

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.

Sanjay T. Sharma
  • 22,857
  • 4
  • 59
  • 71
2

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.)

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • Using Enum Do you mean something like Constants.Foo.valueOf("S_R"); I tried that and didnt work. It returns "S_R" – Pit Digger Apr 27 '11 at 15:18
  • @user608576 get rid of Constants completely. Just Foo.valueOf("S_R"). It should return a `Foo` object on which you can call `getType()` and `getDuration()` – Bozho Apr 27 '11 at 15:27
  • @user608576: no, it does **not** return "S_R" (or at least not the `String` "S_R"). It returns the enum value `S_R` of which you'd get the `type` and/or `duration` using the appropriate getter methods, which you'd have to add). – Joachim Sauer Apr 28 '11 at 08:50
1

If you really must do this (and it's unlikely), you would have to use the Java "reflection" APIs.

Alnitak
  • 334,560
  • 70
  • 407
  • 495