Skip to content
This repository was archived by the owner on Jan 20, 2023. It is now read-only.

Commit f3dd759

Browse files
committed
KConstructorの取り出しを切り出し
1 parent 61a398e commit f3dd759

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

src/main/kotlin/com/mapk/core/Functions.kt

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
package com.mapk.core
22

3+
import com.mapk.annotations.KConstructor
34
import kotlin.reflect.KClass
45
import kotlin.reflect.KFunction
56
import kotlin.reflect.KParameter
67
import kotlin.reflect.full.companionObject
78
import kotlin.reflect.full.functions
9+
import kotlin.reflect.full.primaryConstructor
10+
import kotlin.reflect.jvm.jvmName
811

912
inline 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+
2650
fun KParameter.getKClass(): KClass<*> = type.classifier as KClass<*>

0 commit comments

Comments
 (0)