Created
March 27, 2018 19:00
-
-
Save fredy-mederos/b74e8c2f2ca2f0f5d5910bcb694cbdbf to your computer and use it in GitHub Desktop.
Koin java utility functions to inject components and properties in java classes.
This file contains hidden or 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
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example in java: