反射方式调用enum的方法

版权声明:转载请注明出处 https://blog.csdn.net/h2604396739/article/details/83825148

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

枚举代码如下:

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方法获取实体类

猜你喜欢

转载自blog.csdn.net/h2604396739/article/details/83825148
今日推荐