We can solve this problem with reflections. Below snippet return the name of a public static final constant defined in a class or an interface by its value.
Find the below working application.
AppConfigs.java
package com.sample.app.constants;
public interface AppConfigs {
public static final String APP_VERSION = "1.23";
public static final Integer FIRST_RELEASE_YEAR = 2019;
}
GetConstantNameByValue.java
package com.sample.app;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import com.sample.app.constants.AppConfigs;
public class GetConstantNameByValue {
public static String getConstantName(Class<?> clazz, Object value)
throws IllegalArgumentException, IllegalAccessException {
for (Field field : clazz.getDeclaredFields()) {
// Get the field modifier constant
int modifierConstant = field.getModifiers();
if (Modifier.isStatic(modifierConstant) && Modifier.isPublic(modifierConstant)
&& Modifier.isFinal(modifierConstant)) {
if (field.get(null).equals(value)) {
return field.getName();
}
}
}
throw new IllegalArgumentException("value not found or it is not a public static final");
}
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
String constantName = getConstantName(AppConfigs.class, 2019);
System.out.println(constantName);
constantName = getConstantName(AppConfigs.class, "1.23");
System.out.println(constantName);
}
}
Output
FIRST_RELEASE_YEAR APP_VERSION
No comments:
Post a Comment