Home > Mobile >  How to get only declared members (not inherited) with Kotlin Reflection?
How to get only declared members (not inherited) with Kotlin Reflection?

Time:03-17

Is there any way to get only the declared members of a class (not inherited) with Kotlin Reflection?

Something equivalent to getDeclaredMethods(), or ...Fields(), in Java, but for members and JVM free, which:

Returns an array containing Method objects reflecting all the declared methods of the class ... but excluding inherited methods.

Or like a binding flag, such as BindingFlags.DeclaredOnly of dotnet.

CodePudding user response:

Because the reflection is based on the class, So the following is only for the kotlin/JVM, not suitable for the Kotlin/JS or Kotlin/Native.

For the Kotlin/JS it supports limit, for detail, you can see this document

The only supported parts of the API are: (::class),KType and typeOf

Firstly, you can use the SomeClass::class.java.declaredMethods to get the getDeclaredMethods. That is the java method. Because the Kotlin file after compiled it is still a class. so you can directly use it.

You can also add the kotlin reflect to get the KClass, then use the declaredFunctions to get. Here is the 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

For how to get the KClass, you can use the following code

 Class.forName("mypackage.MyClass").kotlin.declaredFunctions

Besides the method, the other property you can also get. such as

  • declaredMembers

Returns all functions and properties declared in this class. Does not include members declared in supertypes.

  • allSuperclasses
  • functions

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.

you can read the document using it.

  • Related