怎样取得JAVA类里的常量名 -- 动态取得方式
如我给定一个名字,用这个名字构造常量的名字,然后取得此常量的值例:public static final test_11 = "ahbc";public String getValue(String code){
  retrun ("test_"+code) -- 怎样返回 "ahbc"值 code 是动态传入的
}

解决方案 »

  1.   

    你是在什么地方做这个getValue?当前对象么?试试import java.lang.reflect.*; public class TestConst
    { public static final String test_11 = "ahbc"; public String getValue(String code){
    String name = "test_"+code;
    try
    {
    Field field = this.getClass().getField(name);
    return field.get(this).toString();
    }
    catch (Exception ex)
    {
    return "";
    }
    }
    public static void main(String[] args)
    {
    TestConst tc = new TestConst();
    System.out.println("11:" + tc.getValue("11"));
    System.out.println("22:" + tc.getValue("22"));
    }
    }