1. 程式人生 > >反射方式呼叫enum的方法

反射方式呼叫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方法獲取實體類