11package com.mapk.core
22
3+ import com.mapk.annotations.KConstructor
34import kotlin.reflect.KClass
45import kotlin.reflect.KFunction
56import kotlin.reflect.KParameter
67import kotlin.reflect.full.companionObject
78import kotlin.reflect.full.functions
9+ import kotlin.reflect.full.primaryConstructor
10+ import kotlin.reflect.jvm.jvmName
811
912inline fun <reified A : Annotation > KClass <* >.getAnnotatedFunctionsFromCompanionObject (): Pair <Any , List <KFunction <* >>>? {
1013 return this .companionObject?.let { companionObject ->
@@ -23,4 +26,25 @@ inline fun <reified A : Annotation, T> Collection<KFunction<T>>.getAnnotatedFunc
2326 return filter { function -> function.annotations.any { it is A } }
2427}
2528
29+ @Suppress(" UNCHECKED_CAST" )
30+ fun <T : Any > KClass<T>.getKConstructor (): Pair <Any ?, KFunction <T >> {
31+ val constructors = ArrayList <Pair <Any ?, KFunction <T >>>()
32+
33+ this .getAnnotatedFunctionsFromCompanionObject<KConstructor >()?.let { (instance, functions) ->
34+ functions.forEach {
35+ constructors.add(instance to it as KFunction <T >)
36+ }
37+ }
38+
39+ this .constructors.getAnnotatedFunctions<KConstructor , T >().forEach {
40+ constructors.add(null to it)
41+ }
42+
43+ if (constructors.size == 1 ) return constructors.single()
44+
45+ if (constructors.isEmpty()) return null to this .primaryConstructor!!
46+
47+ throw IllegalArgumentException (" ${this .jvmName} has multiple ${KConstructor ::class .jvmName} ." )
48+ }
49+
2650fun KParameter.getKClass (): KClass <* > = type.classifier as KClass <* >
0 commit comments