com.github.xphsc.lang.EnumUtil Maven / Gradle / Ivy
package com.github.xphsc.lang;
import com.github.xphsc.util.PropertyUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
/**
* Created by ${huipei.x} on 2017-6-19.
*/
public class EnumUtil {
private EnumUtil() {
throw new AssertionError("No " + this.getClass().getName() + " instances for you!");
}
public static , T> E getEnumByPropertyValueIgnoreCase(Class enumClass, String propertyName, T specifiedValue) {
return getEnumByPropertyValue(enumClass, propertyName, specifiedValue, true);
}
public static , T> E getEnumByPropertyValue(Class enumClass, String propertyName, T specifiedValue) {
return getEnumByPropertyValue(enumClass, propertyName, specifiedValue, false);
}
private static , T> E getEnumByPropertyValue(Class enumClass, String propertyName, T specifiedValue, boolean ignoreCase) {
Validate.notNull(enumClass, "enumClass can\'t be null!", new Object[0]);
Validate.notBlank(propertyName, "propertyName can\'t be null/empty!", new Object[0]);
Enum[] enumConstants = (Enum[])enumClass.getEnumConstants();
Enum[] messagePattern = enumConstants;
int var6 = enumConstants.length;
for(int var7 = 0; var7 < var6; ++var7) {
Enum e = messagePattern[var7];
Object propertyValue = PropertyUtil.getProperty(e, propertyName);
if(isEquals(propertyValue, specifiedValue, ignoreCase)) {
return (E) e;
}
}
return null;
}
private static boolean isEquals(Object propertyValue, T specifiedValue, boolean ignoreCase) {
if(propertyValue != null && specifiedValue != null) {
if(propertyValue == specifiedValue) {
return true;
} else {
String propertyValueString = propertyValue.toString();
String specifiedValueString = specifiedValue.toString();
return ignoreCase? StringUtils.equalsIgnoreCase(propertyValueString, specifiedValueString):StringUtils.equals(propertyValueString, specifiedValueString);
}
} else {
return propertyValue == specifiedValue;
}
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy