动态变量命名Java

编程入门 行业动态 更新时间:2024-10-23 23:27:19
本文介绍了动态变量命名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

本文发布于:2023-11-28 07:28:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641475.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   动态   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!