在Java中动态分配其他变量的变量值

时间:2011-08-27 06:55:20

标签: java

让我假装我有以下内容:

public class Something{

    private final String VALUE_AAA = "ABC";
    private final String VALUE_BBB = "DEF";
    private final String VALUE_CCC = "GHI";

    public String getValue(String param) {

    }
}

现在我想要将值BBB传递给 getValue 作为回报 DEF

这可能吗?我不想要if - else语句。我讨论过BeanUtils,但我不确定。

谢谢, Hauke

3 个答案:

答案 0 :(得分:3)

也许你可以使用HashMap,

public class Something{

    protected final HashMap<Integer, String>() hashMap = new HashMap<Integer, String>(){{
        put(new Integer(1),"ABC");
        put(new Integer(2),"DEF");
        put(new Integer(3),"GHI");
    }}

    public String getValue(Integer nr) {
        return hashMap.get(nr);
    }
}

编辑

似乎这些值集在类本身中是预先定义的,For String参数作为输入可以使用:

public class Something{

protected final HashMap<String, String> hashMap = new HashMap<String, String>(){{
    put("AAA","ABC");
    put("BBB","DEF");
    put("CCC","GHI");
}};

public String getValue(String nr) {
    return hashMap.get(nr);
}

}

我已经跳过了“Value_”,因为如果您决定使用HashMap,则不需要变量名称,只需要密钥。

答案 1 :(得分:0)

您可以使用反射:获取当前对象的类,按名称查找字段,然后在当前对象中提取此字段的值:

public class Something {

  private final String VALUE_AAA = "ABC";
  private final String VALUE_BBB = "DEF";
  private final String VALUE_CCC = "GHI";

  public String getValue(String param) throws Exception {
     return (String) this.getClass().getDeclaredField("VALUE_" + param).get(this);
  }
}

更多细节: http://download.oracle.com/javase/1,5.0/docs/api/java/lang/Class.html#getDeclaredField(java.lang.String

答案 2 :(得分:0)

抱歉,工作代码:

public class HundM
{
    protected final static HashMap <String, String> hm = new HashMap <String, String> (); 

    public static String getValue (String param) {
        return hm.get (param);
    }

    public static void main (String args[])
    {
        hm.put ("AAA", "ABC");
        hm.put ("BBB", "DEF");
        hm.put ("CCC", "GHI");
        System.out.println (getValue ("BBB"));
    }
}