Skip to content

Instantly share code, notes, and snippets.

@Galaxer
Last active March 16, 2018 13:45
Show Gist options
  • Save Galaxer/fa4e2e656d5cdbbb2d8c0a8cabc8ff7f to your computer and use it in GitHub Desktop.
Save Galaxer/fa4e2e656d5cdbbb2d8c0a8cabc8ff7f to your computer and use it in GitHub Desktop.
Kotlin extension to import a Kodein module only if it exists
/**
* Import a Kodein module if it exists. We're not catching any exceptions in this method so it will
* fail fast. If a Kodein module doesn't import, the app will probably crash soon after this method
* executes anyway. If the app crashes here, it will be easier to debug.
*/
fun Kodein.Builder.importIfExists(qualifiedClassName: String, fieldName: String) {
val moduleClass = Class.forName(qualifiedClassName)
val moduleField = moduleClass.declaredFields.find { field ->
field.name == fieldName
}
if (moduleField == null) {
Timber.w("Kodein module field \"$fieldName)\" not found in class \"$qualifiedClassName\"")
return
}
val moduleClassInstance = moduleClass.newInstance()
moduleField.isAccessible = true
import(moduleField.get(moduleClassInstance) as Kodein.Module)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment