io.github.firefang.power.common.util.EnumUtil Maven / Gradle / Ivy
package io.github.firefang.power.common.util;
import java.util.Optional;
import java.util.function.BiPredicate;
/**
* 枚举工具类
*
* @author xinufo
*
*/
public abstract class EnumUtil {
private static final BiPredicate extends Enum>, String> STRICT = (e, n) -> {
return e.name().equals(n);
};
private static final BiPredicate extends Enum>, String> NOT_STRICT = (e, n) -> {
return e.name().equalsIgnoreCase(n);
};
public static > T fromString(Class enumType, String name) {
return fromString(enumType, name, false);
}
@SuppressWarnings("unchecked")
public static > T fromString(Class enumType, String name, boolean strict) {
BiPredicate p;
if (strict) {
p = (BiPredicate) STRICT;
} else {
p = (BiPredicate) NOT_STRICT;
}
for (T e : enumType.getEnumConstants()) {
if (p.test(e, name)) {
return e;
}
}
return null;
}
public static > Optional fromStringOptional(Class enumType, String name) {
return Optional.ofNullable(fromString(enumType, name, false));
}
public static > Optional fromStringOptional(Class enumType, String name, boolean strict) {
return Optional.ofNullable(fromString(enumType, name, strict));
}
}