Show fields from kotlin class


#1

I'm trying to display the available fields from this kotlin class using reflection.

public class MyClass {   val fieldA: String = ""   val fieldB: String = "" }

fun showFields(clazz: Class<out Any>) {
  println("Class: " + clazz.getName())
  val fields = clazz.getDeclaredFields()

  fields.forEach {
  field ->
  val fieldType = field.getType()

  &nbsp;&nbsp;println("Name: " + field.getName())

  }
}

fun main(args: Array<String>) {
  showFields(javaClass<MyClass>())
}


I’m using getDeclaredFields(), it will display $kotlinClass and the remaining fields.

What should be the kotlin way to list fields or methods from kotlin class(i’m trying to find annotation for the field too) without $kotlinClass?

Regards,
Reza


#2

At the moment the only convenient way is filtering out synthetic members manually (java.lang.reflect.Member.isSynthetic). The proper API is work in progress, subscribe to KT-5759 for updates on this issue


#3

Thank you, i'm using your suggestion to filter the fields.