动态变量名 Java [英] Dynamic variable names Java

查看:35
本文介绍了动态变量名 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆