Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

Dynamic variable names 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
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...