当枚举类型是Class时,如何使用Java反射? [英] How to use Java reflection when the enum type is a Class?
本文介绍了当枚举类型是Class时,如何使用Java反射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这很简单,但我以前没有使用过枚举的反射。
枚举看起来像这样:
public enum PropertyEnum {
SYSTEM_PROPERTY_ONE(property.one.name,property.one.value),
SYSTEM_PROPERTY_TWO(property.two.name,property.two。值);
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;
}
}
调用一个常数使用反射的方法?
解决方案
import java.lang.reflect.Method;
class EnumReflection
{
public static void main(String [] args)
throws异常
{
Class& ?> clz = Class.forName(test.PropertyEnum);
/ *使用Java 1.5中添加的方法。 * /
Object [] consts = clz.getEnumConstants();
/ *枚举常数按照声明的顺序排列。 * /
Class<?> sub = consts [0] .getClass();
方法mth = sub.getDeclaredMethod(getDefaultValue);
String val =(String)mth.invoke(consts [0]);
/ *证明它有效。 * /
System.out.println(getDefaultValue+
val.equals(PropertyEnum.SYSTEM_PROPERTY_ONE.getDefaultValue()));
}
}
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()));
}
}
这篇关于当枚举类型是Class时,如何使用Java反射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文