本文介绍了动态变量命名Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何能够检索具有动态名称的变量的值
How will I be able to retrieve the value of a variable which has a dynamic name
例如,我有常量列表
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推荐答案
使用带有变量名称的普通HashMap作为其值的字符串。或者使用EnumMap将枚举作为键,将值作为值。 AFAIK,这是使用Java时最接近的。当然,你可以搞乱反思,但IMO的地图方法更合乎逻辑。
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.
更多推荐
动态变量命名Java
发布评论