美文网首页架构
spring项目结构设计-枚举工具类

spring项目结构设计-枚举工具类

作者: jinelei | 来源:发表于2020-05-13 17:33 被阅读0次
    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
        }
    
    }
    

    相关文章

      网友评论

        本文标题:spring项目结构设计-枚举工具类

        本文链接:https://www.haomeiwen.com/subject/lrkonhtx.html