Double new_val = 10.0;
String a = "new";
String b = "val";
Double v1 = 25.0;
Double result = 0.0;
Public void getVal() {
//String variable c contain double variable name
String c = a+"_"+b;
//I want to get c's value as 10.0 as its a variable already defined
result = v1*c;
}
"c" String value contain variable name "new_val" and that is used for further
最佳答案
如果问题是,您是否可以在运行时知道其名称来获取变量的值,那么好消息....是的,您肯定可以...您需要做一个叫做 REFFLECTION 的东西...
这允许您作为开发人员对类进行介绍,甚至“浏览”类所持有的所有信息
在你的情况下,你需要通过名称找到一个“变量”(或字段)并读取它的值......
查看文档以获取更多信息,我建议您考虑是否真的需要这样做...通常,当您想访问其他类的信息而不是浏览自己时,会使用反射.. .
您也许可以稍微重新设计应用程序并定义一些常量和方法,以便其他人可以看到您向他们公开的内容并使他们可用...
示例:
public class Jung {
Double new_val = 10.0;
String a = "new";
String b = "val";
Double v1 = 25.0;
Double result = 0.0;
public void getVal() {
// String variable c contain double variable name
String c = a + "_" + b;
Double cAsVal = 0.0;
try {
cAsVal = dale(c);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
result = v1.doubleValue() * cAsVal.doubleValue();
System.out.println(result);
}
public static void main(String[] args) {
Jung j = new Jung();
j.getVal();
}
public Double dale(String c)
throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
Field field = this.getClass().getDeclaredField(c);
field.setAccessible(true);
Object value = field.get(this);
return (Double) value;
}
}
关于java - 将字符串值转换为变量名 |字符串值包含变量名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38539314/