views:

195

answers:

1

This might not have a major usecase in projects ,but i was just trying a POC kind of project where in i get the key code,and using its value i want to print the key name on screen so i want to relive myself off writing switch cases ,so thinking of going by reflection. Is there a way to get the constant integer of interface's name using its value?

KeyPressed(int i)
{string pressedKeyName = getPressedKey(i);
System.out.println(pressedKeyName );

}

+3  A: 

I can think of two better solutions to this than using reflection.

  1. Any decent IDE will auto-fill in switch statements for you. I use IntelliJ and it does this (you just press ctrl-enter). I'm sure Eclipse/Netbeans have something similar; and

  2. Enums make a far better choice for constants than public static primitives. The added advantage is they will relieve you of this problem.

But to find out what you want via reflection, assuming:

interface Foo {
  public static final int CONST_1 = 1;
  public static final int CONST_2 = 3;
  public static final int CONST_3 = 5;
}

Run:

public static void main(String args[]) {
  Class<Foo> c = Foo.class;
  for (Field f : c.getDeclaredFields()) {
    int mod = f.getModifiers();
    if (Modifier.isStatic(mod) && Modifier.isPublic(mod) && Modifier.isFinal(mod)) {
      try {
        System.out.printf("%s = %d%n", f.getName(), f.get(null));
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      }
    }
  }
}

Output:

CONST_1 = 1
CONST_2 = 3
CONST_3 = 5
cletus
That would not be my choice.Thanks for the effort cletus.But is really want it through reflection
Ravisha
@Ravisha check out the update.
cletus
thats what i was talking about buddy:)
Ravisha