2013-06-28 26 views
1

我需要将诸如"VK_UP"(或简单地说"UP")之类的文本更改/解析为Java中的KeyEvent.VK_UP常量。我不想使用数字38,因为它将被保存在.txt配置文件中,所以任何人都可以重写它。Java:将“VK_UP”更改为KeyEvent.VK_UP

最好的解决办法是有此HashMap:

HashMap<String, Integer> keyConstant; 

,其中关键是名称("VK_UP")和值将是关键的代码(38)。

现在的问题是:我怎样才能得到这张地图,而不用花费所有时间手动创建它?

+0

的反思? [docjar.com/html/api/java/awt/event/KeyEvent.java.html](http://docjar.com/html/api/java/awt/event/KeyEvent.java.html) – jlordo

回答

3

您可以使用反射。

以下的线路中的东西应该工作,SANS异常处理:

public static int parseKeycode(String keycode) { 
    // We assume keycode is in the format VK_{KEY} 
    Class keys = KeyEvent.class; // This is where all the keys are stored. 
    Field key = keys.getDeclaredField(keycode); // Get the field by name. 
    int keycode = key.get(null); // The VK_{KEY} fields are static, so we pass 'null' as the reflection accessor's instance. 
    return keycode; 
} 

或者,你可以使用一个简单的一行:

KeyEvent.class.getDeclaredField(keycode).get(null);