Created
December 6, 2021 18:12
-
-
Save WendyYanto/a8a28d4df2cc0b4bcddadb6727e6aad4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object Injector { | |
fun <T : InjectorModule, R : Any> inject(kClass: KClass<T>, entryPointClass: R) { | |
// get all provider methods | |
val methods = kClass.java.declaredMethods | |
.filter { method -> method.isAnnotationPresent(Provides::class.java) } | |
// construct module instance | |
val moduleInstance = kClass.java.newInstance() | |
// construct and cache dependencies | |
val dependencies: MutableMap<Class<*>, Any> = mutableMapOf() | |
methods.forEach { method -> | |
dependencies[method.returnType] = method.invoke(moduleInstance) | |
} | |
// Inject dependencies | |
entryPointClass.javaClass.fields.filter { field -> | |
field.isAnnotationPresent(Inject::class.java) | |
}.forEach { field -> | |
// field.type will return Class<*> | |
field.set(entryPointClass, dependencies[field.type]) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment