package com.zr.entity;
/**
* 仅用于测试类,从实际项目中抽出来的
* @author zr
*
*/
public class Constant {
/**
* 参数校验枚举类
* @author zr
*
*/
public static enum ResultObjectType {
//成功
SUCC(0),
//失败,异常
ERROR(1),
//参数错误
PARAMERROR(2),
//数据为空
NODATA(9);
private Integer value;
private ResultObjectType(Integer value) {
this.value = value;
}
public Integer getDesc() {
return this.value;
}
}
/**
* 参数校验枚举类
* @author zr
* @date 2018年9月17日
*/
public static enum ParamValidate {
CheckLength("checkLength",0),
IsAccId("IsAccId",1),
IsAge("IsAge",2),
IsEmail("IsEmail",3),
IsIdCard("IsIdCard",4),
IsPhoneNo("IsPhoneNo",5),
IsPostCode("IsPostCode",6),
IsPwd("IsPwd",7);
// 成员变量
private String desc;
private int index;
// 构造方法
private ParamValidate(String name, int index) {
this.desc = name;
this.index = index;
}
// 覆盖方法
@Override
public String toString() {
return this.index + "_" + this.desc;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
}
枚举
package com.zr.test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test {
public static void main(String[] args) {
test();
}
public static void test(){
String substring = "ParamValidate";
//根据反射获取常量类
try {
Class c2 = Class.forName("com.zr.entity.Constant");
//获取常量类中的所有内部类
Class innerClazz[] = c2.getDeclaredClasses();
//遍历内部内
for (Class class1 : innerClazz) {
//判断类是不是枚举类
if(class1.isEnum()){
//获取内部内的类名,在这里其实就是获取枚举类
String simpleName = class1.getSimpleName();
//反射获取枚举类
Class<Enum> clazz = (Class<Enum>)Class.forName("com.zr.entity.Constant$"+simpleName);
//获取所有枚举实例
Enum[] enumConstants = clazz.getEnumConstants();
//根据方法名获取方法
Method getCode = clazz.getMethod("getDesc");
for (Enum enum1 : enumConstants) {
//得到枚举实例名
String name2 = enum1.name();
//执行枚举方法获得枚举实例对应的值
Object invoke = getCode.invoke(enum1);
System.out.println(name2+":"+invoke.toString());
}
}
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
原文地址:https://blog.51cto.com/haidragon/2396899