Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get interface constant name using its value

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. 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);
}
like image 287
Ravisha Avatar asked Apr 08 '10 12:04

Ravisha


People also ask

Can interface be used for constants?

It's possible to place widely used constants in an interface. If a class implements such an interface, then the class can refer to those constants without a qualifying class name. This is only a minor advantage. The static import feature should always be considered as a replacement for this practice.

Can an interface have constant variables?

In an interface, we're allowed to use: constants variables. abstract methods. static methods.

Can interface contains constants in Java?

A Java interface contains static constants and abstract methods.

How do you declare a constant in an interface?

The most common way to define a constant is in a class and using public static final . One can then use the constant in another class using ClassName. CONSTANT_NAME . Constants are usually defined in upper cases as a rule, atleast in Java.


1 Answers

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
like image 156
cletus Avatar answered Oct 09 '22 23:10

cletus