安卓如何在Java中使用反射调用Kotlin对象方法?
我想在下面的代码中使用java反射调用setApiHelper方法。我该怎么做
object PlayerUtils {
private var apiHelper: String? = null
fun setApiHelper(apiHelper: String) {
this.apiHelper = apiHelper
println(apiHelper)
}
fun getApiHelper(): String? {
return this.apiHelper
}
}
我的实施
private static void testingPlayerUtils() {
try {
Class<?> cls = Class.forName("reflection.PlayerUtils");
cls.newInstance();
Method method = cls.getDeclaredMethod("setApiHelper");
method.invoke(cls.newInstance(), "TESTING");
} catch (ClassNotFoundException | NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
这是一个错误
java.lang.IllegalAccessException: Class TestingReflection2 can not access a member of class reflection.PlayerUtils with modifiers "private"
at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:102)
at java.lang.Class.newInstance(Class.java:436)
at TestingReflection2.testingPlayerUtils(TestingReflection2.java:20)
at TestingReflection2.main(TestingReflection2.java:14)
# 1 楼答案
您需要为下面的方法设置accessible true-
# 2 楼答案
通常,当您想使用Java代码访问Kotlin中声明的
object
时,可以执行以下代码片段:话虽如此,为了使用反射访问Java中的
PlayerUtils
方法,您需要首先访问它的静态成员INSTANCE
您可以通过使用
Field
fromClass
声明来实现,如下所示:有关详细信息,请参阅here