4

有没有办法在Java中实现这种代码?

int foo = 3;
String data = "foo";
System.out.println(StringToReference(data));

并打印3

编辑:具体来说,我想解析 a Stringorchar并返回一个int代表 a KeyEvent。例如,我希望能够做到这一点:

for(char c : "hello")
    new Robot().keyPress(StringToReference("KeyEvent.VK_"+c));
4

6 回答 6

6

在不确切知道您要完成什么的情况下,这是我认为您可以获得的最接近的结果:

Map<String, Integer> map = new HashMap<String, Integer>();

map.put("foo", 3);

System.out.println(map.get("foo"));
于 2013-05-23T19:23:29.000 回答
2

通常,在 Java 中,您不能按名称引用变量(作为字符串,在运行时;Perl 称之为“软引用”)。但在某些情况下(字段,而不是局部变量),您可以通过反射获得类似的行为。

为了您的意图,您可以这样做:

public static int getKeyEventVK(char c) throws 
                      IllegalArgumentException, SecurityException, 
                      IllegalAccessException, NoSuchFieldException {
    return KeyEvent.class.getField("VK_" + 
               String.valueOf(c).toUpperCase()).getInt(null);

}

public static void main(String[] args) throws Exception{
    System.out.println(getKeyEventVK('h'));
    System.out.println(KeyEvent.VK_H);
}       

但请记住,键入的字符串可以触发多个 VK_* 事件(例如 shift)。并且都H对应hVK_H,因此这不会完全模仿通过键入字符串触发的事件hello(更不用说非字母数字字符、死键、退格键等)

于 2013-05-23T19:46:25.360 回答
1

以下是如何通过反射来做到这一点:

char c = "C";
Robot rob = new Robot();
Field field = KeyEvent.class.getDeclaredField("VK_"+c);         
int i = field.getInt(null);
rob.keyPress(i);
于 2013-05-23T19:26:21.607 回答
1

我明白你在做什么。其他答案都不是正确的。

您希望获得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;
}

所有这些代码都未经测试。祝你好运。我猜你仍然有一些过于复杂的事情发生,但希望这会让你指向正确的方向。

于 2013-05-23T19:56:34.543 回答
0

您可以使用以下代码:

int foo = 3;
String data = Integer.toString(foo);

这将允许将 int 存储在 String 文件中。我想你可以将它传递给你的方法并从中返回你想要的任何东西。

虽然上面的代码可以工作,但我不确定你什么时候会使用它。

于 2013-05-23T19:23:31.270 回答
-1

你可以使用java反射。

场反射

       Class<?> c = Class.forName("YOUR_CLASS_NAME");
       Field f = c.getField("FOO");
       System.out.println(f.getInt());
于 2013-05-23T19:22:29.890 回答