¶Ô±ÈÐÂÎļþ |
| | |
| | | package com.lf.server.helper; |
| | | |
| | | import org.apache.commons.logging.Log; |
| | | import org.apache.commons.logging.LogFactory; |
| | | |
| | | import java.lang.reflect.Method; |
| | | |
| | | /** |
| | | * æä¸¾å¸®å©ç±» |
| | | * @author WWW |
| | | */ |
| | | public class EnumHelper { |
| | | private static final String GETTER_PREFIX = "get"; |
| | | |
| | | private static Log log = LogFactory.getLog(EnumHelper.class); |
| | | |
| | | /** |
| | | * æ ¹æ®åç§°è·åæä¸¾ |
| | | * |
| | | * @param clazz æä¸¾ç±»å |
| | | * @param name æä¸¾çåç§°ï¼å¦ï¼SqlParamTypeä¸çAND |
| | | * @return è¿åæä¸¾å¼ |
| | | */ |
| | | public static <T extends Enum<T>> T nameOf(Class<T> clazz, String name) { |
| | | return Enum.valueOf(clazz, name); |
| | | } |
| | | |
| | | /** |
| | | * æ ¹æ®å±æ§å+å¼è·åæä¸¾ |
| | | * |
| | | * @param clazz æä¸¾ç±»å |
| | | * @param propertyName åæ®µ,å¦name,id |
| | | * @param value å¼,å¦å¼ ä¸ |
| | | * @return è¿åæä¸¾å¼ |
| | | */ |
| | | public static <T extends Enum<T>> T getByString(Class<T> clazz, String propertyName, String value) { |
| | | String getterMethodName = GETTER_PREFIX + StringHelper.firstCharToUpperCase(propertyName); |
| | | T result = null; |
| | | try { |
| | | T[] arr = clazz.getEnumConstants(); |
| | | Method targetMethod = clazz.getDeclaredMethod(getterMethodName); |
| | | String typeCodeVal = null; |
| | | for (T entity : arr) { |
| | | typeCodeVal = targetMethod.invoke(entity).toString(); |
| | | if (typeCodeVal.contentEquals(value)) { |
| | | result = entity; |
| | | break; |
| | | } |
| | | } |
| | | } catch (Exception ex) { |
| | | log.error(ex.getMessage(), ex); |
| | | } |
| | | return result; |
| | | } |
| | | |
| | | /** |
| | | * æ ¹æ®æ´æ°è·åæä¸¾ |
| | | * |
| | | * @param clazz æä¸¾ç±»å |
| | | * @param propertyName åæ®µ,å¦ age |
| | | * @param value å¼,å¦18 |
| | | * @return è¿åæä¸¾å¼ |
| | | */ |
| | | public static <T extends Enum<T>> T getByInt(Class<T> clazz, String propertyName, int value) { |
| | | String getterMethodName = GETTER_PREFIX + StringHelper.firstCharToUpperCase(propertyName); |
| | | T result = null; |
| | | try { |
| | | T[] arr = clazz.getEnumConstants(); |
| | | Method targetMethod = clazz.getDeclaredMethod(getterMethodName); |
| | | int typeCodeVal; |
| | | for (T entity : arr) { |
| | | typeCodeVal = Integer.parseInt(targetMethod.invoke(entity).toString()); |
| | | if (typeCodeVal == value) { |
| | | result = entity; |
| | | break; |
| | | } |
| | | } |
| | | } catch (Exception ex) { |
| | | log.error(ex.getMessage(), ex); |
| | | } |
| | | return result; |
| | | } |
| | | } |