Come usare la riflessione Java quando il tipo enum è una classe?
-
02-07-2019 - |
Domanda
Stavo usando un enum in cui la costante era una classe. Avevo bisogno di invocare un metodo sulla costante ma non potevo introdurre una dipendenza del tempo di compilazione e l'enum non era sempre disponibile in fase di esecuzione (parte dell'installazione opzionale). Pertanto, volevo usare la riflessione.
Questo è facile, ma non avevo mai usato la riflessione con gli enum.
L'enum era simile a questo:
public enum PropertyEnum {
SYSTEM_PROPERTY_ONE("property.one.name", "property.one.value"),
SYSTEM_PROPERTY_TWO("property.two.name", "property.two.value");
private String name;
private String defaultValue;
PropertyEnum(String name) {
this.name = name;
}
PropertyEnum(String name, String value) {
this.name = name;
this.defaultValue = value;
}
public String getName() {
return name;
}
public String getValue() {
return System.getProperty(name);
}
public String getDefaultValue() {
return defaultValue;
}
}
Qual è un esempio di invocazione di un metodo della costante usando la riflessione?
Soluzione
import java.lang.reflect.Method;
class EnumReflection
{
public static void main(String[] args)
throws Exception
{
Class<?> clz = Class.forName("test.PropertyEnum");
/* Use method added in Java 1.5. */
Object[] consts = clz.getEnumConstants();
/* Enum constants are in order of declaration. */
Class<?> sub = consts[0].getClass();
Method mth = sub.getDeclaredMethod("getDefaultValue");
String val = (String) mth.invoke(consts[0]);
/* Prove it worked. */
System.out.println("getDefaultValue " +
val.equals(PropertyEnum.SYSTEM_PROPERTY_ONE.getDefaultValue()));
}
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow