samedi 22 décembre 2018

How can I get all implementations of an interface at runtime in Kotlin

I know I can get all subclasses of a sealed class in Kotlin, but I'm looking for a way to get all implementations of an interface.

So instead of ...

sealed class HotDrinkFactory {
    abstract fun prepare(amount: Int): HotDrink
}

class TeaFactory : HotDrinkFactory() {
    override fun prepare(amount: Int): HotDrink {
        ...
    }
}

class CoffeeFactory : HotDrinkFactory() {
    override fun prepare(amount: Int): HotDrink {
        ...
    }
}

fun main(args: Array<String>) {
    val hotDrinkFactories = HotDrinkFactory::class.sealedSubclasses
    hotDrinkFactories.forEach { println(it::class.qualifiedName) }
}

... I would like to have

interface HotDrinkFactory {
    fun prepare(amount: Int): HotDrink
}

class TeaFactory : HotDrinkFactory {
    override fun prepare(amount: Int): HotDrink {
        ...
    }
}

class CoffeeFactory : HotDrinkFactory {
    override fun prepare(amount: Int): HotDrink {
        ...
    }
}

fun main(args: Array<String>) {
    val hotDrinkFactories = HotDrinkFactory::class.<<< Something here? >>>
    hotDrinkFactories.forEach { println(it::class.qualifiedName) }
}





Aucun commentaire:

Enregistrer un commentaire