I want to invoke setApiHelper method in the below code using java reflection. How can I do so?
object PlayerUtils {
private var apiHelper: String? = null
fun setApiHelper(apiHelper: String) {
this.apiHelper = apiHelper
println(apiHelper)
}
fun getApiHelper(): String? {
return this.apiHelper
}
}
My Implementation
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();
}
}
this gives an error
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)
Usually when you want to access object
declared in Kotlin using Java code, you can do like below code snippet:
PlayerUtils.INSTANCE.setApiHelper("");
//or
PlayerUtils.INSTANCE.getApiHelper();
Now that being said, in order to access methods of PlayerUtils
in Java using reflection, you'll need to access it's static member called INSTANCE
first.
And you can do that by using Field
from Class
declaration, something like below:
Class<?> cls = Class.forName("reflection.PlayerUtils");
Object instance = cls.getField("INSTANCE");
Method method = cls.getDeclaredMethod("setApiHelper");
method.invoke(instance, "TESTING");
Refer here for detailed info.
You need to set accessible true for the method as below -
Class<?> cls = Class.forName("reflection.PlayerUtils");
cls.newInstance();
Method method = cls.getDeclaredMethod("setApiHelper");
method.setAccessible(true);
method.invoke(cls.newInstance(), "TESTING");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.