I wonder is there any better way to parse enum when you don't have Generic and have only KProperty1<T, *>
?
I have found / come up with solution like this:
enum Car {
BMW, AUDI
}
val property = properties[fieldName] as? KProperty1<T, *>
val instanceKClass = property.returnType.jvmErasure
if (instanceKClass.java.isEnum) {
parseEnum(property.javaField!!.type as Class<Enum<*>>, "BMW")
}
fun parseEnum(enumClass: Class<Enum<*>>, value: Any?): Enum<*>? {
val enumClz = enumClass.enumConstants
return try {
enumClz.first { it.name == value }
} catch (ignored: Exception) {
throw IlligalArgumentException("there is no such enum")
}
}
I'm trying to extract enum value from string in Kotlin via reflection and I want to find best possible way of doing this
P.S. I'm looking for advice how to do it more efficient and nice, because I'm not really satisfied with this way.
Aucun commentaire:
Enregistrer un commentaire