com.yixan.base.web.utils.EnumUtil Maven / Gradle / Ivy
package com.yixan.base.web.utils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Pattern;
import org.springframework.context.ApplicationContext;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.context.ContextLoader;
import com.yixan.tools.common.util.KeyString;
import com.yixan.tools.common.util.VerifyUtil;
/**
* 枚举工具类
*
* @author zhaohuihua
* @version V1.0 2015年9月30日
*/
public abstract class EnumUtil {
private static final Pattern SEPARATOR = Pattern.compile(",");
/**
* 解析枚举字符串
*
*
* EnumUtil.parse("MALE,FEMALE", Gender.class);
* --> [ Gender.MALE, Gender.FEMALE ]
*
*
* @param enums 枚举字符串
* @param type 枚举类
* @return 枚举列表
*/
public static > List parse(String enums, Class type) {
if (VerifyUtil.isBlank(enums)) {
return null;
}
String[] array = SEPARATOR.split(enums);
List list = new ArrayList<>();
for (String i : array) {
list.add(Enum.valueOf(type, i));
}
return list;
}
/**
* 获取枚举对应的描述
*
*
* EnumUtil.getEnumsResource(Gender.class, UserState.class);
* --> { Gender:[{key:"MALE",value:"男"},{key:"FEMALE",value:"女"}], UserState:[...] }
*
*
* @param list
* @return
*/
@SafeVarargs
public static Map> getEnumsResource(Class extends Enum>>... list) {
Map> map = new HashMap<>();
Locale locale = LocaleContextHolder.getLocale();
ApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
for (Class extends Enum>> clazz : list) {
map.put(clazz.getSimpleName(), getEnumResource(clazz, context, locale));
}
return map;
}
/**
* 获取枚举对应的描述
*
*
* EnumUtil.getEnumResource(Gender.class);
* --> [{key:"MALE",value:"男"},{key:"FEMALE",value:"女"}]
*
*
* @param list
* @return
*/
public static List getEnumResource(Class extends Enum>> clazz) {
Locale locale = LocaleContextHolder.getLocale();
MessageSource context = ContextLoader.getCurrentWebApplicationContext();
try {
return getEnumResource(clazz, context, locale);
} catch (NoSuchMessageException e) {
if (!locale.getLanguage().equals(Locale.CHINESE.getLanguage())) {
return getEnumResource(clazz, context, Locale.CHINA);
} else {
throw e;
}
}
}
private static List getEnumResource(Class extends Enum>> clazz, MessageSource context,
Locale locale) {
List list = new ArrayList<>();
Enum>[] enums = clazz.getEnumConstants();
for (Enum> e : enums) {
if (!"NULL".equals(e.name().toUpperCase())) {
String key = clazz.getSimpleName() + "." + e.name();
String txt = context.getMessage(key, null, locale);
list.add(new KeyString(e.name(), txt));
}
}
return list;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy