mercredi 27 novembre 2019

Kotlin reflection for object class gives null

I'm diving into reflection and I've met the following issue with this object class:

object Dict {

     fun getAll(): Map<String, List<String>> {
        return mapOf(
            "Mark" to listOf("Banana"),
            "John" to listOf("Strawbery", "Pie"),
            "Lily" to listOf("Apple", "Banana", "Pie"),
        )
    }
}

knowing the package canonical name of this class I can get this method:

val dictClass = Class.forName("com.example.util.Dict")
val getAllRelationsMethod = relationsClass.getMethod("getAll")
val peopleWithMeals = getAllRelationsMethod.invoke(null) // this line gives error

I got the following exception: java.lang.NullPointerException: null receiver

I'm passing the null into the invoke() method because it doesn't need a class instance to call (like static in java). Does the method call differs from Java here somehow? Didn't find a tip around the Internet so that's why I'm asking here. Thanks in advance! :)





Aucun commentaire:

Enregistrer un commentaire