如何使用 Kotlin Reflection 只获取声明的成员(不是继承的)?
How to get only declared members (not inherited) with Kotlin Reflection?
有什么方法可以使用 Kotlin 反射仅获取 class(未继承)的已声明 成员?
相当于 getDeclaredMethods()
或 ...Fields()
,在 Java 中,但对于 成员 和 JVM 免费,其中:
Returns an array containing Method objects reflecting all the declared methods of the class ... but excluding inherited methods.
或者像绑定标志,比如dotnet的 BindingFlags.DeclaredOnly
。
因为反射是基于class,所以下面只针对kotlin/JVM,不适合Kotlin/JS或Kotlin/Native.
对于Kotlin/JS支持limit,具体可以看这个
document
The only supported parts of the API are: (::class),KType and typeOf
首先,您可以使用 SomeClass::class.java.declaredMethods
获取
getDeclaredMethods。那就是 java 方法。因为编译后的Kotlin文件还是一个class。所以你可以直接使用它。
也可以添加kotlin reflect获取KClass,然后使用declaredFunctions
获取。这是 Document
Returns all functions declared in this class. If this is a Java class, it includes all non-static methods (both extensions and non-extensions) declared in the class and the superclasses, as well as static methods declared in the class
关于如何获取KClass,可以使用如下代码
Class.forName("mypackage.MyClass").kotlin.declaredFunctions
除了方法,其他属性你也可以得到。比如
- 声明成员
Returns all functions and properties declared in this class. Does
not include members declared in supertypes.
- 全超classes
- 函数
Returns all functions declared in this class, including all non-static methods declared in the class and the superclasses, as well as static methods declared in the class.
您可以使用它阅读文档。
有什么方法可以使用 Kotlin 反射仅获取 class(未继承)的已声明 成员?
相当于 getDeclaredMethods()
或 ...Fields()
,在 Java 中,但对于 成员 和 JVM 免费,其中:
Returns an array containing Method objects reflecting all the declared methods of the class ... but excluding inherited methods.
或者像绑定标志,比如dotnet的 BindingFlags.DeclaredOnly
。
因为反射是基于class,所以下面只针对kotlin/JVM,不适合Kotlin/JS或Kotlin/Native.
对于Kotlin/JS支持limit,具体可以看这个 document
The only supported parts of the API are: (::class),KType and typeOf
首先,您可以使用 SomeClass::class.java.declaredMethods
获取
getDeclaredMethods。那就是 java 方法。因为编译后的Kotlin文件还是一个class。所以你可以直接使用它。
也可以添加kotlin reflect获取KClass,然后使用declaredFunctions
获取。这是 Document
Returns all functions declared in this class. If this is a Java class, it includes all non-static methods (both extensions and non-extensions) declared in the class and the superclasses, as well as static methods declared in the class
关于如何获取KClass,可以使用如下代码
Class.forName("mypackage.MyClass").kotlin.declaredFunctions
除了方法,其他属性你也可以得到。比如
- 声明成员
Returns all functions and properties declared in this class. Does not include members declared in supertypes.
- 全超classes
- 函数
Returns all functions declared in this class, including all non-static methods declared in the class and the superclasses, as well as static methods declared in the class.
您可以使用它阅读文档。