Skip to content

Instantly share code, notes, and snippets.

@WendyYanto
Created December 6, 2021 18:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WendyYanto/a8a28d4df2cc0b4bcddadb6727e6aad4 to your computer and use it in GitHub Desktop.
Save WendyYanto/a8a28d4df2cc0b4bcddadb6727e6aad4 to your computer and use it in GitHub Desktop.
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