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);
}
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.
In an interface, we're allowed to use: constants variables. abstract methods. static methods.
A Java interface contains static constants and abstract methods.
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.
I can think of two better solutions to this than using reflection.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With