object EnumUtils {
private val logger: Logger = LoggerFactory.getLogger(EnumUtils::class.java)
@Suppress("UNCHECKED_CAST")
fun <T> valueOf(clazz: Class<*>, any: Any): T {
if (!clazz.isEnum) {
logger.error("{} is not enum class", clazz.simpleName)
throw BasicException(BasicError.CLASS_TYPE_NOT_SUPPORT, "class must be enum class")
}
val enumConstants = clazz.enumConstants
val fields = enumConstants.joinToString(", ") { o -> (o as Enum<*>).name }
val result = enumConstants.filter { o ->
when (any) {
is String -> (o as Enum<*>).name.equals(any, ignoreCase = true)
is Int -> (o as Enum<*>).ordinal == any
else -> false
}
}.toList()
if (result.isNullOrEmpty()) {
logger.error("{} not found in enum {}, all available fields: [{}]", any, clazz.simpleName, fields)
throw BasicException(BasicError.ENUM_NOT_FOUND, "$any not found in enum ${clazz.simpleName}")
}
return result.first() as T
}
}
网友评论