java.lang.NullPointerException: null receiver

最近在使用反射上遇到的错误,当反射调用一个kotlin声明的object类时,然后再反射直接调用某个方法

val targetClass = loadDexClass("xx")
val method = targetClass?.getDeclaredMethod("init", Context::class.java, DexClassLoader::class.java, String::class.java, Boolean::class.java)
method?.isAccessible = true
method?.invoke(null, context.applicationContext, mDexClassLoader, mDexPath, true)

就会报java.lang.NullPointerException: null receiver,因为kotlin的object是单例模式,所以不先实例化是会报错的

正确修改:

val targetClass = loadDexClass("xx")
val constructor = targetClass?.getDeclaredConstructor()
constructor?.isAccessible = true
val targetActivity = constructor?.newInstance()
val method = targetClass?.getDeclaredMethod("init", Context::class.java, DexClassLoader::class.java, String::class.java, Boolean::class.java)
method?.isAccessible = true
method?.invoke(targetActivity, context.applicationContext, mDexClassLoader, mDexPath, true)

你可能感兴趣的:(java.lang.NullPointerException: null receiver)