Ank*_*oor 1 java reflection android 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
}
}
Run Code Online (Sandbox Code Playgroud)
我的实施
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();
}
}
Run Code Online (Sandbox Code Playgroud)
这给出了一个错误
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)
Run Code Online (Sandbox Code Playgroud)
通常当你想object使用Java代码访问Kotlin中声明的时候,你可以像下面的代码片段一样执行:
PlayerUtils.INSTANCE.setApiHelper("");
//or
PlayerUtils.INSTANCE.getApiHelper();
Run Code Online (Sandbox Code Playgroud)
话虽这么说,为了PlayerUtils使用反射访问 Java 中的方法,您需要INSTANCE首先访问它的静态成员。
您可以通过使用FieldfromClass声明来做到这一点,如下所示:
Class<?> cls = Class.forName("reflection.PlayerUtils");
Object instance = cls.getField("INSTANCE");
Method method = cls.getDeclaredMethod("setApiHelper");
method.invoke(instance, "TESTING");
Run Code Online (Sandbox Code Playgroud)
请参阅此处了解详细信息。
| 归档时间: |
|
| 查看次数: |
2171 次 |
| 最近记录: |