通过枚举' field'通过Kotlin的反射

发布于 2025-01-29 02:52:51 字数 796 浏览 2 评论 0原文

,很容易以kpropertykproperty1这样的方式传递属性

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文