[英]How to use Java reflection when the enum type is a Class?
I was using an enum in which the constant was a Class. 我正在使用枚举,其中常量是一个类。 I needed to invoke a method on the constant but could not introduce a compile time dependency and the enum was not always available at runtime (part of optional install).
我需要在常量上调用一个方法但是不能引入编译时依赖项,并且枚举在运行时并不总是可用(可选安装的一部分)。 Therefore, I wanted to use reflection.
因此,我想用反射。
This is easy, but I hadn't used reflection with enums before. 这很容易,但我之前没有使用枚举的反射。
The enum looked something like this: 枚举看起来像这样:
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;
}
}
What is an example of invoking a method of the constant using reflection? 使用反射调用常量方法的示例是什么?
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()));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.