final static int
DRAGON = 5,
SNAKE = 6;
String this_item = "DRAGON";
int item_value = super_func(this_item);//must be 5
是否可以实现this super_func
,如上所示?
还是我要求太多?
编辑:
我不允许使用枚举。我可以:
a)使用地图(如某人指出的那样,或2个数组列表)或
b)以某种方式进行此操作(但似乎不可能)。
尽管在技术上可以使用反射来完成此操作,但我强烈建议您重新考虑您的结构,并考虑其他答案中已提及的替代方法之一。
最简单的可能是使用地图
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
public class VariableNameTest
{
private static final Map<String,Integer> map;
static
{
Map<String, Integer> m = new LinkedHashMap<String, Integer>();
m.put("DRAGON",5);
m.put("SNAKE",6);
map = Collections.unmodifiableMap(m);
}
public static void main(String[] args)
{
System.out.println(getValue("DRAGON"));
System.out.println(getValue("SNAKE"));
System.out.println(getValue("Boo!"));
}
public static int getValue(String name)
{
Integer i = map.get(name);
if (i == null)
{
// Do some error handling here!
}
return i;
}
}
但是,如果您打算使用其他功能扩展它,则可能应该引入一个类,例如在https://stackoverflow.com/a/23846279/3182664中建议的类
仅出于完整性考虑:不建议使用反射解决方案!
import java.lang.reflect.Field;
public class VariableNameTest
{
static final int DRAGON = 5;
static final int SNAKE = 6;
public static void main(String[] args)
{
System.out.println(getValue("DRAGON"));
System.out.println(getValue("SNAKE"));
System.out.println(getValue("Boo!"));
}
private static int getValue(String name)
{
try
{
Class<?> c = VariableNameTest.class;
Field f = c.getDeclaredField(name);
return f.getInt(null);
}
catch (NoSuchFieldException e)
{
// Many things
e.printStackTrace();
}
catch (SecurityException e)
{
// may cause
e.printStackTrace();
}
catch (IllegalArgumentException e)
{
// this to
e.printStackTrace();
}
catch (IllegalAccessException e)
{
// fail horribly
e.printStackTrace();
}
return 0;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句