反射调用枚举

662 阅读1分钟

代码中存在很多结构相似的枚举,需要分别调用其方法名称相同的方法,所以选择使用反射调用

枚举代码如下:

/** * 根据code获取枚举对象(ps:使用此方法,枚举类需实现getBizConstantDisplay方法)
 *
 * @param clazzName 枚举类名
 * @param code      枚举值
 * @return 枚举对象
 */public static BizConstantDisplay getBizDisplayByCode(String clazzName, Integer code) {
    // 这里是 包路径+枚举名称
    BizConstantDisplay result = null;
    try {
        Class<?> clazz = Class.forName("xxx.xxx.xxx" + clazzName);
        Method method = clazz.getDeclaredMethod("getBizConstantDisplay", Integer.class);
        // 错误的方式,枚举对应的class没有newInstance方法,会报NoSuchMethodException,应该使用getEnumConstants方法
        // Object o = aClass.newInstance();NoSuchMethodException
        // 妥协点1:入参直接传class,会导致mapstruct生成的impl类中找不到符号,因此采用class.forName方案
        Object[] oo = clazz.getEnumConstants();
        result = (BizConstantDisplay) method.invoke(oo[0], code);
    } catch (Exception e) {
        logger.warn("获取枚举失败 clazzName {} code {} e:", clazzName, code, e);
    }
    return result;
}

注意: 

 枚举实体类的获取:枚举对应的class没有newInstance方法,会报NoSuchMethodException,应该使用getEnumConstants方法获取实体类 上面为什么不是直接调用枚举呢?因为一个枚举很简单,如果是有十几个类似UserTypeEnum的枚举呢?

此时就会很麻烦,不如类似下面代码,直接获取枚举名称,然后通过反射来调用,代码会简化很多