0

すべてのキーjava.awt.event.KeyEventをマップに取得する方法はありますか?

次のようなリフレクションを使用してみました:

 for (Field f : KeyEvent.class.getDeclaredFields()) {
            try 
            {
                map.put((int)f.getInt(f), f.getName());
            } 
            catch (IllegalArgumentException | IllegalAccessException ex) {
                Logger.getLogger(KeyCollection.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

しかし、私は得ました:

java.lang.IllegalAccessException: Class com.util.KeyCollection can not access a member of class java.awt.event.KeyEvent with modifiers "private"

更新: assylias コード例を使用して思いついたのは次のとおりです。

 for (Field f : KeyEvent.class.getDeclaredFields()) {
            try {
                if (java.lang.reflect.Modifier.isStatic(f.getModifiers()) && f.getType() == int.class && f.getName().startsWith("VK")) {
                    f.setAccessible(true);
                    map.put((int)f.get(null), f.getName());
                }
            } catch (IllegalArgumentException | IllegalAccessException ex) {
                ex.printStackTrace();
            }
        }
4

1 に答える 1

3

あなたのアプローチを使用して、最初にフィールドにアクセスできるようにする必要があります。

f.setAccessible(true);

しかし、フィールドを取得しようとする方法にも問題があります。以下の例は問題なく動作し、必要に応じて変更できます。

public static void main(String[] args) {
    Map<Object, String> map = new HashMap<>();

    for (Field f : KeyEvent.class.getDeclaredFields()) {
        try {
            if (java.lang.reflect.Modifier.isStatic(f.getModifiers())) {
                f.setAccessible(true);
                map.put(f.get(null), f.getName());
            }
        } catch (IllegalArgumentException | IllegalAccessException ex) {
            ex.printStackTrace();
        }
    }
    System.out.println(map);
}
于 2013-01-13T11:55:28.020 に答える