Kotlin-动态实例化所有内部类

Kotlin-动态实例化所有内部类,kotlin,reflection,Kotlin,Reflection,下面是我希望解决的情况——一个服务正在使用JSON并进行一些处理。基于其中一个JSON字段中的字符串值,我想实例化实现接口的许多类中的一个 本质上,我试图让JSON输入能够控制使用哪种功能 我当前解决方案的简化版本如下 interface A{ val name: String fun doSomething() } class choseImplementation(val jsonChoice: String){ inner class B: A{

下面是我希望解决的情况——一个服务正在使用JSON并进行一些处理。基于其中一个JSON字段中的字符串值,我想实例化实现接口的许多类中的一个

本质上,我试图让JSON输入能够控制使用哪种功能

我当前解决方案的简化版本如下

interface A{
    val name: String
    fun doSomething()
}

class choseImplementation(val jsonChoice: String){
    inner class B: A{
        override val name = "B"
        override fun doSomething(){// Do B things}
    }

    inner class C: A{
        override val name = "C"
        override fun doSomething(){// Do C things}
    }

    init {
        // Instantiate B and C
        // Compare B.name and C.name with jsonChoice
        // Choose the name that matches jsonChoice and expose the instantiated class
        // The exposed class will be used in downstream processing
    }
}
choseImplementation被赋予一个字符串,并公开系统要使用的正确实现

现在我正在手动实例化init函数中的每个类,然后进行比较,这意味着我必须在两个地方更改代码,添加D类,然后将其合并到init函数中

我希望能够添加一个新的内部类(D实现a),并将其自动添加到实例化和选择的过程中

欢迎使用此模板之外的解决方案

谢谢

可以使用获取嵌套在特定类中的所有类。然后,您需要过滤结果,以便使用

然后,通常使用或查找构造函数或所需签名来实例化类,但是,由于这将是一个
内部
类,请注意,它的所有构造函数都有一个额外的第一个(可能是单个)参数,您需要将外部类的实例传递给该参数

加在一起,它看起来像:

class ChooseImplementation(val jsonChoice: String) {
    /* Inner classes omitted... */ 

    init {
        val innerClass = this::class.nestedClasses
            .filter { it.isInner }
            .find { it.simpleName == jsonChoice }
            ?: error("Could not find inner class $jsonChoice")

        val instance = innerClass.primaryConstructor!!.call(this)

        /* Use the instance... */
    }
}
请注意,要使用Kotlin reflection API,您需要依赖于
Kotlin reflect

,您可以使用获取嵌套在特定类中的所有类。然后,您需要过滤结果,以便使用

然后,通常使用或查找构造函数或所需签名来实例化类,但是,由于这将是一个
内部
类,请注意,它的所有构造函数都有一个额外的第一个(可能是单个)参数,您需要将外部类的实例传递给该参数

加在一起,它看起来像:

class ChooseImplementation(val jsonChoice: String) {
    /* Inner classes omitted... */ 

    init {
        val innerClass = this::class.nestedClasses
            .filter { it.isInner }
            .find { it.simpleName == jsonChoice }
            ?: error("Could not find inner class $jsonChoice")

        val instance = innerClass.primaryConstructor!!.call(this)

        /* Use the instance... */
    }
}
请注意,要使用Kotlin reflection API,您需要依赖于
Kotlin reflect