How to obtain all subclasses of a given sealed class?

后端 未结 4 1707
孤街浪徒
孤街浪徒 2021-02-02 05:56

Recently we upgraded one of our enum class to sealed class with objects as sub-classes so we can make another tier of abstraction to simplify code. However we c

4条回答
  •  天涯浪人
    2021-02-02 06:57

    A wise choice is using ServiceLoader in kotlin. and then write some providers to get a common class, enum, object or data class instance. for example:

    val provides = ServiceLoader.load(YourSealedClassProvider.class).iterator();
    
    val subInstances =  providers.flatMap{it.get()};
    
    fun YourSealedClassProvider.get():List{/*todo*/};
    

    the hierarchy as below:

                    Provider                    SealedClass
                       ^                             ^
                       |                             |
                --------------                --------------
                |            |                |            |
            EnumProvider ObjectProvider    ObjectClass  EnumClass
                |            |-------------------^          ^
                |                                     |
                |-------------------------------------------|
                                     
    

    Another option, is more complicated, but it can meet your needs since sealed classes in the same package. let me tell you how to archive in this way:

    1. get the URL of your sealed class, e.g: ClassLoader.getResource("com/xxx/app/YourSealedClass.class")
    2. scan all jar entry/directory files in parent of sealed class URL, e.g: jar://**/com/xxx/app or file://**/com/xxx/app, and then find out all the "com/xxx/app/*.class" files/entries.
    3. load filtered classes by using ClassLoader.loadClass(eachClassName)
    4. check the loaded class whether is a subclass of your sealed class
    5. decide how to get the subclass instance, e.g: Enum.values(), object.INSTANCE.
    6. return all of instances of the founded sealed classes

提交回复
热议问题