dimanche 15 mai 2022

Pass enum 'field' via reflection in Kotlin

In Kotlin, it's easy to pass a property as a KProperty or KProperty1 like this for example:

inline fun <TRet, reified TOwner> getName(property: KProperty1<TOwner, TRet>): String {
    return "${TOwner::class.simpleName}.${property.name}"
}

And then given the following type:

class Example(val exampleName: String)

I could call getName(Example::exampleName) which would return Example.exampleName.

Is there any way to do this with enums?

Say I had the following enum class:

enum class ExampleEnum { VALUE1, VALUE2 }

Is there any way to get ExampleEnum::VALUE1 or some useful reflection object about the values in ExampleEnum? I essentially want to be able to access the declaring KClass (or java class) and the field being accessed in the enum, just by passing one argument.

The alternative is to write something like getName(ExampleEnum::class, "VALUE1") which is verbose and doesn't play well with refactorings/renames. Also, please note the getName is just an example, the actual use case is a bit more general.





Aucun commentaire:

Enregistrer un commentaire