有一个接口(interface),定义键盘代码。每个按钮都有代码。
public interface KeyMap{
private static final int A = 23;
private static final int B = 24;
//other keys
...
}
但我的问题是:如何通过数字(23,24,...)获取字母(A,B,...)。 类似于:
public String getKey(int value);
我尝试解决创建 map 的问题,但随后需要一次又一次地初始化完整的 map 。我考虑过 Java Reflect,但找不到正确的方法。
最佳答案
Java 反射是可能的,但它会非常慢,因为您必须迭代所有字段才能获取具有正确值的字段。
另一个建议:
enum KeyCode {
A(23),
...;
private int code;
private static final Map<Integer, KeyCode> keys = new HashMap<Integer, KeyCode>();
static {
for(KeyCode code : values()) {
keys.put(code.code, code);
}
}
private KeyCode(int code) {
this.code = code;
}
public static KeyCode getKey(int code) {
return keys.get(code);
}
}
这使您可以简单地执行...
KeyCode code = KeyCode.getCode(23);
String name = code.name(); // assuming not null here, should be "A"
这会非常快,等等。但是当然,另一个问题是,如果您不能使用现有的框架。例如,据我所知,Swing 已经做了一些键映射。
编辑:
好的,因为您似乎必须使用预定义的 class ,反射实际上似乎是唯一的方法...此方法将允许您按值获取所有字段名称的映射。
public static Map<Object, String> getFieldsByValue(Class<?> clz) {
Map<Object, String> map = new HashMap<Object, String>();
// Remember: Class.getField() returns only PUBLIC fields
for (Field field : clz.getFields()) {
// Check if it's a static variable
if (Modifier.isStatic(field.getModifiers())) {
// Add other checks, for example for "integer", if you want.
try {
// field.get(null) returns the value of the field for a static field
map.put(field.get(null), field.getName());
} catch (IllegalArgumentException e) {
// should not happen, as we made sure the field is static
} catch (IllegalAccessException e) {
// should not happen, as we only listed public fields
}
}
}
return map;
}
您可以在静态初始化 block 中调用此方法一次(请参见上面的示例),以创建一次 Map,然后访问它,这使得运行时更好:
static {
keyMap = getFieldsByValue(com.vaadin.event.ShortcutAction.KeyCode.class);
// example
String name = keyMap.get(23); // should be "A"
}
关于java - 按值获取字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32745956/