mercredi 20 novembre 2019

Get singleton object via companion using reflection and class name

As the title stands, I want to get a singleton instance via reflection using the class name. Let's say I have this class:

abstract class MyClass : BaseClass() { 

    abstract fun getExampleObject() : ExampleObject

    companion object { 

        @Volatile
        private var INSTANCE: MyClass? = null
        fun getInstance(context: Context): MyClass {
            return INSTANCE ?: synchronized(this) {
                val instance = Base.myBuilder(context.applicationContext, MyClass::class.java).build()

                INSTANCE = instance
                instance
            }
        }
    }
}

Now, knowing the class name like this val strClass = MyClass::class.qualifiedName.toString()

I would like to achieve this: MyClass.getInstance(this).getExampleObject().doSomeStuff() but via reflection.

I tried this:

val strClass = MyClass::class.qualifiedName.toString()
val myClass = Class.forName(strClass)
val companion = myClass::class.companionObject

in that case, companion is null.

In the other case this: val companion = MyClass::class.companionObject gives me the actual companion but I cannot do that because in the place where it should be done the compiler does know only the class name.





Aucun commentaire:

Enregistrer un commentaire