简体   繁体   English

如何在运行时替换类?

[英]How to replace a class at runtime?

I have 2 classes.我有2节课。 I want to replace one, class A so that ANY instance of it will actually behave like class B .我想替换一个, AA以便它的任何实例实际上都表现得像B类。

class A {
    fun test() = "a"
}

class B { 
    fun test() = "b"
}

I was trying to use the ClassLoader to do this but I couldn't get the system to call MyClassLoader .我试图使用ClassLoader来做到这一点,但我无法让系统调用MyClassLoader

class MyClassLoader() : ClassLoader() {

    @Throws(ClassNotFoundException::class)
    override fun loadClass(name: String): Class<*>? {
        if (name == "com.myapp.A") {
            return B::class.java
        } else return super.loadClass(name)
    }
}

This has to happen at compile time or runtime because I cannot manually replace every instance of A for B .这必须在编译时或运行时发生,因为我无法手动将A每个实例替换为B (This is a minimalist example of the problem). (这是问题的一个极简示例)。 A cannot be removed, this is a requirement. A不能删除,这是一个要求。

So how do I attach MyClassLoader so that the system uses it?那么如何附加MyClassLoader以便系统使用它呢?

I tried: Thread.currentThread().setContextClassLoader(MyClassLoader()) but the MyClassLoader doesn't get called.我试过: Thread.currentThread().setContextClassLoader(MyClassLoader())MyClassLoader没有被调用。

i do not know what it will use for but for low scale ,you can try to have only on object that contain the methods and properties of both classes like example我不知道它将用于什么,但是对于小规模,您可以尝试仅使用包含两个类的方法和属性的对象,例如 example

val classType2 = 1
class AB{
    fun testA() = "a"
    fun testB() = "b"
    val classType1 = 1 

   fun test() {
     if(classType1 ==1){testA()}
     else{testB()}    
   }

}

you can add fun to change the class type or,您可以添加乐趣来更改课程类型,或者,

if you want to change all instances at the same replace classType1 with classType2 at if contition then change value of classType2.如果要同时更改所有实例,请在 if 条件下将 classType1 替换为 classType2,然后更改 classType2 的值。

i hope that我希望

You can use the Factory design pattern.您可以使用工厂设计模式。 Depending on what kind of class instance you want you can load/return it at runtime from the Factory class static method.根据您想要的类实例类型,您可以在运行时从 Factory 类静态方法加载/返回它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM