Sometimes we may want to inspect the available constructors on a type. Perhaps we need to create a type that has a constructor that requires values. Or perhaps we want to determine which fields are needed to create an instance of a type at runtime. Or, similarly, perhaps we want to see if a class can be created from the parameters we have available.
We can return a list of all the constructors declared on a given type by using the constructors property available on the KClass type. This property returns a list of KFunction reflective instances, since constructors are themselves functions, albeit defined in a special way:
fun <T : Any> printConstructors(kclass: KClass<T>) { kclass.constructors.forEach { println(it.parameters) } }
The preceding example simply iterates over each constructor, printing out the parameters it...