How to get an enum value from a string value in Java?

前端 未结 27 2606
旧巷少年郎
旧巷少年郎 2020-11-21 10:53

Say I have an enum which is just

public enum Blah {
    A, B, C, D
}

and I would like to find the enum value of a string, for example

27条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-21 11:53

    Kotlin Solution

    Create an extension and then call valueOf("value"). If the type is invalid, you'll get null and have to handle it

    inline fun > valueOf(type: String): T? {
        return try {
            java.lang.Enum.valueOf(T::class.java, type)
        } catch (e: Exception) {
            null
        }
    }
    

    Alternatively, you can set a default value, calling valueOf("value", MyEnum.FALLBACK), and avoiding a null response. You can extend your specific enum to have the default be automatic

    inline fun > valueOf(type: String, default: T): T {
        return try {
            java.lang.Enum.valueOf(T::class.java, type)
        } catch (e: Exception) {
            default
        }
    }
    

    Or if you want both, make the second:

    inline fun > valueOf(type: String, default: T): T = valueOf(type) ?: default
    

提交回复
热议问题