ServiceLoader

Provides functionality for dynamically loading service implementations using the Service Provider Interface (SPI) mechanism.

It works in conjunction with Service and ServiceProvider annotations:

  • interfaces or abstract classes annotated with Service can be retrieved using this loader.

  • implementations of these services are identified using the ServiceProvider annotation.

Usage:

// module: A
@Service
interface SimpleService {
fun saySomethingSweet()
}

// module: A, B or even in a library!
@ServiceProvider
object SimpleServiceImpl : SimpleService {
override fun saySomethingSweet() {
println("Kotlin is Awesome")
}
}

// module: A, B, C or may be not even in your codebase...
fun main() {
ServiceLoader.load<SimpleService>().forEach { service ->
service.saySomethingSweet()
}
}

Functions

Link copied to clipboard
inline fun <T : Any> load(): List<T>
fun <T : Any> load(cls: KClass<T>): List<T>

Retrieves a list of services of the specified type T, which must be annotated with Service. Providers of these services must be annotated with ServiceProvider.