com.jtransc.injector.Injector.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of jtransc-utils Show documentation
Show all versions of jtransc-utils Show documentation
JVM AOT compiler currently generating JavaScript, C++, Haxe, with initial focus on Kotlin and games.
package com.jtransc.injector
import com.jtransc.error.invalidOp
@Suppress("UNCHECKED_CAST")
class Injector() {
val maps = hashMapOf, () -> Any>(
Injector::class.java to { this@Injector }
)
inline fun get(): T = getInstance(T::class.java)
inline fun get(default: () -> T): T = if (T::class.java in maps) getInstance(T::class.java) else default()
fun getInstance(clazz: Class): T {
if (clazz !in maps) mapImplementation(clazz, clazz)
return this.maps[clazz]!!() as T
}
internal fun createInstance(clazz: Class): T {
val c = clazz.constructors.firstOrNull() ?: invalidOp("No constructors")
return c.newInstance(*(c.parameterTypes.map { this.getInstance(it) }).toTypedArray()) as T
}
private fun getAllAnnotations(clazz: Class<*>): List {
return if (clazz.superclass == null) {
clazz.annotations.toList()
} else {
clazz.annotations.toList() + getAllAnnotations(clazz.superclass)
} + clazz.interfaces.flatMap { getAllAnnotations(it) }
}
fun mapImplementation(classInterface: Class<*>, classImpl: Class<*>) {
val isSingleton = (getAllAnnotations(classImpl).filterIsInstance().isNotEmpty())
var cached: Any? = null
this.maps[classInterface] = {
if (isSingleton) {
if (cached == null) cached = createInstance(classImpl)
cached!!
} else {
createInstance(classImpl)
}
}
}
fun mapInstances(vararg objs: Any) = run { for (obj in objs) mapInstance(obj) }
fun mapInstance(obj: T): T = mapInstance(obj, obj.javaClass)
fun mapInstance(obj: T, type: Class): T = obj.apply { maps[type] = { obj } }
inline fun mapImpl() = mapImplementation(TInt::class.java, TImpl::class.java)
}
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.CLASS)
annotation class Singleton()
© 2015 - 2025 Weber Informatics LLC | Privacy Policy