反射方式调用enum的方法
代码中存在很多结构相似的枚举,需要分别调用其方法名称相同的方法,所以选择使用反射调用
枚举代码如下:
package com.ruisitech.bi.enums.bireport; /** * @author:mazhen * @date:2018/9/13 11:46: * @description:用户类型枚举 */ public enum UserTypeEnum { Geek("0","geek"),Boss("1","boss"),Other("2","other-userType"); String value; String meaning; UserTypeEnum(String value,String meaning){ this.value=value; this.meaning=meaning; } public static String getMeaning(String value){ for(UserTypeEnum userType : UserTypeEnum.values()){ if(userType.value.equals(value)){ return userType.meaning; } } return ErrorConstant.errorMessage; } }
反射方式调用getMeaning方法如下:
static void inovkeEnum() throws NoSuchMethodException, ClassNotFoundException, InvocationTargetException, IllegalAccessException, InstantiationException { // 这里是 包路径+枚举名称 Class<?> aClass = Class.forName("com.ruisitech.bi.enums.bireport.UserTypeEnum"); Method getMeaning = aClass.getDeclaredMethod("getMeaning", String.class); // 错误的方式,枚举对应的class没有newInstance方法,会报NoSuchMethodException,应该使用getEnumConstants方法 //Object o = aClass.newInstance();NoSuchMethodException Object[] oo = aClass.getEnumConstants(); Object invoke = getMeaning.invoke(oo[0],"0"); }
注意:
枚举实体类的获取:枚举对应的class没有newInstance方法,会报NoSuchMethodException,应该使用getEnumConstants方法获取实体类
上面为什么不是直接调用枚举呢?因为一个枚举很简单,如果是有十几个类似UserTypeEnum的枚举呢?此时就会很麻烦,不如类似下面代码,直接获取枚举名称,然后通过反射来调用,代码会简化很多
for(Map.Entry<String,String> entry : rhQueryConditionMap.entrySet()){ if(!StringUtils.isEmpty(entry.getValue()) ){ try { aClass = Class.forName("com.ruisitech.bi.enums.bireport."+entry.getKey()+"Enum"); } catch (ClassNotFoundException e) { logger.error("com.ruisitech.bi.enums.bireport."+entry.getKey()+"Enum获取反射异常:"+e); continue; } split = entry.getValue().split(","); getMeaning = aClass.getDeclaredMethod("getMeaning", String.class); enumConstants = aClass.getEnumConstants(); for(String str:split){ buffer.append((String)getMeaning.invoke(enumConstants[0],str)).append(","); } // 此处的处理,为了在查询的时候可以直接使用in语法,而不用转为list使用in rhQueryConditionMap.put(entry.getKey(),"("+entry.getValue()+")"); } }