An improved method in java for obtaining value through code in enumeration class

This article is limited to self-study, and there is nothing worth learning, just " feeling "

At work, I often encounter certain constant values, such as administrators, project managers, developers, ordinary users, etc. For such constants with many options, we usually find a corresponding number. to represent, for example,
0,1,2,3,4.

For this kind of one-to-one correspondence, we generally use enumeration classes to achieve.

Before today, my enumeration classes were written like this

public enum  UserEnum {
    
    
    GENERAL_USER(1, "普通用户"),
    BAN(2,"被封号")ADMIN(3,"管理员");

    private Integer code;
    private String value;

    UserEnum(Integer code, String value) {
    
    
        this.code = code;
        this.value = value;
    }

    public static String getValue(Integer code) {
    
    
        if (code == null) {
    
    
            return "";
        }
        for (UserEnum user : UserEnum.values()) {
    
    
            if (user.code.intValue() == code.intValue()) {
    
    
                return user.value;
            }
        }
        return "";
    }
}

But I found that once there are more enumeration classes, you need to write a getValue method in each enumeration class, which is too troublesome, so I thought about whether I could write a public method to achieve this requirement:

public static String getEnumValueByCode(Class<? extends Enum<?>> clazz, Integer code) {
    
    
        for (Enum<?> enumConstant : clazz.getEnumConstants()) {
    
    
            try {
    
    
                if (Integer.parseInt(String.valueOf(clazz.getMethod("getCode").invoke(enumConstant))) == code.intValue()) {
    
    
                    return String.valueOf(clazz.getMethod("getValue").invoke(enumConstant));
                }
            } catch (Exception e) {
    
    
                e.printStackTrace();
            }
        }
        return "";
    }

This method is mainly implemented based on reflection. The two methods getCode and getValue in the enumeration class are obtained through reflection . Of course, the prerequisite for using this method is that these two methods must be present in the enumeration class, otherwise it will be thrown. abnormal.

Although the use of reflection may affect a little performance, but this improves the reusability of the code, in my opinion, the overall advantages outweigh the disadvantages

Guess you like

Origin blog.csdn.net/qq_43649799/article/details/131020302