samedi 17 mars 2018

How to dynamically call kotlin's object(singleton) method?

I have a Kotlin singleton named ApiService like this:

object ApiService {
    private val someApi:SomeApi = SomeApi.create()
    fun getSomeApi():SomeApi{
        return someApi
    }
}

Now I want to call ApiService.getSomeApi dynamically. I did something like this:

val fullClassName = "com.somepackage.ApiService"
val obj = Class.forName(fullClassName)
obj.getMethod("getSomeApi").invoke(obj)

But I got an error like:

Expected receiver of type com.somepackage.ApiService, but got java.lang.Class <com.somepackage.ApiService>

If I hardcode .invoke(ApiService) it will work fine, but is there a way to do this dynamically?





Aucun commentaire:

Enregistrer un commentaire