How to get class properties or fields using reflection in Kotlin/Native?

31 Views Asked by At

I have a class like

class Foo {
  val bar = Bar()

  fun doSomething() {

  }
}

How do I get the fields or properties of the class Foo in doSomething?

Looking into this::class only has little available: autocomplete dropdown

I added the reflect dependency but it does not appear to have done anything:

        val nativeMain by getting {
            dependencies {
                implementation(kotlin("reflect"))
            }
        }

The class I'm writing is going to have a lot of properties which are all handled the same way so I'd like to iterate over them so that I don't have to manually write everything myself in a hard-coded fashion.

2

There are 2 best solutions below

1
sasikumar On

you can use this code instead of this::class.

In your example

bar::reference properties // here you will get

for more reference Reflection

7
Sweeper On

Reflection on Kotlin/Native is very limited. See the documentation pages for the kotlin.reflect package with the "Native" filter. The only useful things you can get out of a KClass are simpleName, qualifiedName, isInstance, cast, and safeCast.

While on the JVM you are forced to put lots of these reflection "metadata" into class files, having all that information emitted into a native binary would increase the size of the binary by a lot. From here, this seems to go against the goals of Kotlin/Native (emphasis mine):

The initial release of K/N will definitely not support Class.forName. The whole idea of K/N is to provide a “closed world” view of the code and enable to build a highly-optimized and compact executable. We believe that use-cases that require reflection in the way that you’ve described are perfectly covered by Kotlin/JVM already. We are not trying to build a better JVM.

As an idea, you can consider using some annotation processing to generate a List<KProperty> for you to use. Something similar is also suggested in this discussion.