我明白你在做什么。其他答案都不是正确的。
您希望获得KeyEvent
给定字符的“正确”常量,并且您希望这样做而不必编写某种可能有数百万行长的查找表。
事实上,反思会帮助你。它会相当慢。但它会完成这项工作。这项工作是否真的需要做是另一个问题。:-)
您想要的功能可能是这样的:
/**
* If possible, returns an {@code int} equal to one of the {@code public
* static final int} constants present in the {@link KeyEvent} class
* whose names start with {@code VK_}.
*
* <p>This implementation does no error handling whatsoever and has not
* been tested or compiled.</p>
*
* <p>This method is placed explicitly in the public domain.</p>
*
* @param c the character to use while searching for a field; no attempt
* will be made by this implementation to validate it in any way
*
* @return a {@link KeyEvent} constant whose name starts with {@code VK_}
*
* @exception Exception for any of a number of possible reasons
*/
public int getKeyEventConstant(final char c) throws Exception {
final Field field = KeyEvent.class.getField(String.format("VK_%S", Character.valueOf(c)));
assert field != null;
return field.getInt(null);
}
String
然后,您可以像下面这样提供它,尽管如果提供的包含字符我上面描述的函数没有被编辑以正确处理异常,您将遇到各种问题:
public toKeyEventCodes(final String s) {
int[] returnValue = null;
if (s != null && !s.isEmpty()) {
final Collection<Integer> codes = new ArrayList<Integer>(s.length());
final char[] chars = s.toCharArray();
assert chars != null;
assert chars.length > 0;
for (final char c : chars) {
if (!Character.isWhitespace(c)) { // TODO: weed out other obvious dumb chars
codes.add(Integer.valueOf(getKeyEventConstant(c)));
}
}
returnValue = codes.toArray(new int[codes.size()]);
}
if (returnValue == null) {
returnValue = new int[0];
}
return returnValue;
}
所有这些代码都未经测试。祝你好运。我猜你仍然有一些过于复杂的事情发生,但希望这会让你指向正确的方向。