Skip to content

Instantly share code, notes, and snippets.

@4sskick
Forked from fredy-mederos/KoinJavaUtils.kt
Created July 18, 2020 10:46
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 4sskick/97706b76aa591609d85e8af486ca62b7 to your computer and use it in GitHub Desktop.
Save 4sskick/97706b76aa591609d85e8af486ca62b7 to your computer and use it in GitHub Desktop.
Koin java utility functions to inject components and properties in java classes.
package com.common.utils
import org.koin.KoinContext
import org.koin.standalone.StandAloneContext
import kotlin.jvm.internal.Reflection
/**
* @author @fredy_mederos
*/
object KoinJavaUtils {
/**
* inject lazily given dependency
*/
@JvmOverloads
@JvmStatic
fun <T> inject(clazz: Class<T>, name: String = ""): Lazy<T> {
return lazy { get(clazz, name) }
}
/**
* Retrieve given dependency
*/
@JvmOverloads
@JvmStatic
fun <T> get(clazz: Class<T>, name: String = ""): T {
val kclazz = Reflection.getOrCreateKotlinClass(clazz)
val koinContext = (StandAloneContext.koinContext as KoinContext)
val beanDefinition = if (name.isBlank())
koinContext.beanRegistry.searchAll(kclazz)
else
koinContext.beanRegistry.searchByName(name)
return koinContext.resolveInstance(kclazz, { emptyMap() }, { beanDefinition }) as T
}
/**
* inject lazily given property
*/
@JvmOverloads
@JvmStatic
fun <T> property(key: String, defaultValue: T? = null): Lazy<T?> {
return lazy { getProperty(key, defaultValue) }
}
/**
* Retrieve given property
*/
@Suppress("UNCHECKED_CAST")
@JvmOverloads
@JvmStatic
fun <T> getProperty(key: String, defaultValue: T? = null): T? {
val koinContext = (StandAloneContext.koinContext as KoinContext)
return koinContext.propertyResolver.properties[key] as T? ?: defaultValue
}
}
@4sskick
Copy link
Author

4sskick commented Jul 18, 2020

Example in java:

MyManager myManager = KoinJavaUtils.get(MyManager.class);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment