How do I reflectively instantiate an enum given an...
# reflect
p
How do I reflectively instantiate an enum given an enum class of type
java.lang.Class<*>
? Can't find a way to make the type checker happy.
m
So what's the code?
p
Couldn't figure out how to call
java.lang.Enum.valueOf()
from Kotlin (given a
java.lang.Class<*>
), but
java.lang.Class.getEnumConstants()
did the trick.
👍 1
j
You can just reference the java.lang:
return java.lang.Enum.valueOf(typeStructure.type as Class<T>, value.asString())
p
Huh? Referencing
java.lang.Enum
isn't the problem; convincing the type checker to pass a
java.lang.Class<*>
to
java.lang.Enum.valueOf
is (give it a try).
j
That's why the cast. It's just I'm using that same line of code in my project
p
I don't understand. To begin with, I don't have a type parameter
T
. All I have is an instance of
java.lang.Class<*>
that I know is an enum type.
I tried such things as
java.lang.Enum.valueOf(clazz as Class<Enum<*>>, "foo")
but couldn't get past the type checker.
m
Why do you want to use
Enum.valueOf()
in the first place? It's not supposed to be used if you don't know the concrete type. There are ways around that but using
Class.getEnumConstants()
should be sufficient.
d
For the record, the key here is the
Nothing
type:
Enum.valueOf(cls as Class<Nothing>, "foo")
p
@diesieben07 thanks, good to know!
@Marc Knaup I was just looking for a solution and had not yet found
getEnumConstants()
.
u