Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: load service #2428

Merged
merged 3 commits into from
Feb 17, 2023
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion mirai-core-utils/src/jvmBaseMain/kotlin/Services.kt
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import kotlin.reflect.full.createInstance
public actual fun <T : Any> loadService(clazz: KClass<out T>, fallbackImplementation: String?): T {
var suppressed: Throwable? = null
return ServiceLoader.load(clazz.java).firstOrNull()
?: ServiceLoader.load(clazz.java, clazz.java.classLoader).firstOrNull()
?: (if (fallbackImplementation == null) null
else runCatching { findCreateInstance<T>(fallbackImplementation) }.onFailure { suppressed = it }.getOrNull())
?: throw NoSuchElementException("Could not find an implementation for service class ${clazz.qualifiedName}").apply {
Expand All @@ -29,10 +30,18 @@ private fun <T : Any> findCreateInstance(fallbackImplementation: String): T {

public actual fun <T : Any> loadServiceOrNull(clazz: KClass<out T>, fallbackImplementation: String?): T? {
return ServiceLoader.load(clazz.java).firstOrNull()
?: ServiceLoader.load(clazz.java, clazz.java.classLoader).firstOrNull()
?: if (fallbackImplementation == null) return null
else runCatching { findCreateInstance<T>(fallbackImplementation) }.getOrNull()
}

public actual fun <T : Any> loadServices(clazz: KClass<out T>): Sequence<T> {
return ServiceLoader.load(clazz.java).asSequence()
return sequence {
val current = ServiceLoader.load(clazz.java).iterator()
if (current.hasNext()) {
yieldAll(current)
} else {
yieldAll(ServiceLoader.load(clazz.java, clazz.java.classLoader))
}
}
}