java Kotlin 反射 - 获取类的所有字段名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39589780/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 04:29:59  来源:igfitidea点击:

Kotlin reflection - getting all field names of a Class

javareflectionkotlin

提问by Ivar Reukers

How can I get a list of a Kotlin data class it's declaredFields? Like Java's getDeclaredFields()

如何获取 Kotlin 数据类的列表declaredFields?像Java的getDeclaredFields()

And if this is possible is it also possible to filter for publicand privatefields? (Like Java's Modifier.isPrivate(field.getModifiers()))

如果这是可能的,是否也可以过滤publicprivate字段?(就像 Java 的Modifier.isPrivate(field.getModifiers())

回答by hotkey

Probably what you want is to get properties of a class, not fields. This can be done as follows:

可能您想要的是获取类的属性,而不是字段。这可以按如下方式完成:

MyClass::class.declaredMemberProperties

Getting fields is also possible through Java reflection:

也可以通过 Java 反射获取字段:

MyClass::class.java.declaredFields

But fields are rather an implementation detail in Kotlin, because some properties might have no backing field.

但是字段在 Kotlin 中更像是一个实现细节,因为某些属性可能没有支持字段



As to the visibility, for properties you can check the getter visibility modifiers:

至于可见性,对于属性,您可以检查 getter 可见性修饰符:

val p = MyClass::class.declaredMemberProperties.first()
val modifiers = p.javaGetter?.modifiers

Note: it's nullin case of a simple private valor @JvmFieldusage. Then you can inspect p.javaFieldinstead.

注意:这是null在简单private val@JvmField用法的情况下。然后你可以检查p.javaField

Then, if modifiersis not null, just check it with Modifier.isPrivate(...).

然后,如果modifiers不是null,只需使用 进行检查Modifier.isPrivate(...)

Properties in Kotlin can have separate visibility modifiers for getter and setter, but a setter access cannot be more permissive than that of the getter, which is effectively the property visibility.

Kotlin 中的属性可以为 getter 和 setter 设置单独的可见性修饰符,但 setter 访问不能比 getter 更宽松,后者实际上是属性可见性。

回答by Jayson Minard

There is indeed documentation available for Kotlin reflection: an overall summary of reflectionand the API docsincluding for the KClass.membersfunction. You can also jump to the declaration of that method and you will see it is documented in the source code as well.

确实有可用于 Kotlin 反射的文档:反射API 文档的总体摘要,包括KClass.members函数。您还可以跳转到该方法的声明,您将看到它也记录在源代码中。

回答by CoolMind

Use MyClass::class.java.declaredFieldsor it's instance: myObject::class.java.declaredFields.

使用MyClass::class.java.declaredFields或它的实例:myObject::class.java.declaredFields