繁体   English   中英

将字符串值转换为变量名| 字符串值包含变量名

[英]convert string value to variable name | string value contain variable name

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”字符串值包含变量名“ new_val”,用于进一步

如果问题是,是否可以在运行时知道变量的名称获取变量的值 ,那么这是个好消息。...是的,可以确定...您将需要执行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;
}
}

你有什么问题

如果您想执行“ 25 * c”,就像用字符串(“ new_val”)插入Double(25)。 它不会工作

如果我是正确的,那么您将无法基于Java中的另一个变量值在代码中使用变量名。 如果需要在变量中使用字符串值,则应创建一个带有字段的类,例如:

class myVariable{
    String name;
    int value;
}

我想将字符串值(“ c”)转换为变量名(Double new_val)

很高兴看到可以使用什么反射来完成工作。

对于您的情况, Map也可以为您解决问题。

public static void main(String args[]){
    HashMap<String, Double> map = new HashMap<String, Double>();
    map.put("new_val", 10.0);

    String a = "new";
    String b = "val";
    Double v1 = 25.0;
    Double result = 0.0;

    //String variable c contain double variable name
    String c = a+"_"+b;
    //String variable c used for calculation
    result = v1 * map.get(c);

    System.out.println(result);
}

选中“将字符串值用作变量名”以获取更多详细信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM