通过枚举' field'通过Kotlin的反射
,很容易以kproperty
或kproperty1
这样的方式传递属性
inline fun <TRet, reified TOwner> getName(property: KProperty1<TOwner, TRet>): String {
return "${TOwner::class.simpleName}.${property.name}"
}
:
class Example(val exampleName: String)
在Kotlin中 :exipplename)将返回xpeame.examplename
。
有什么办法用枚举做到这一点吗?
假设我有以下枚举类别:
enum class ExampleEnum { VALUE1, VALUE2 }
有什么方法可以获取exampleenum :: value1
或涉及示例中的值的一些有用的反射对象
?我本质上希望能够通过通过一个参数来访问声明的kClass
(或Java类)以及在枚举中访问的字段。
替代方法是编写类似getName(exampleenum :: class,“ value1”)
的内容,该是冗长的,并且在重构/重命名的情况下表现不佳。另外,请注意getName
只是一个示例,实际用例更为笼统。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论