lundi 5 avril 2021

How to invoke Kotlin object method using reflection in Java?

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)




Aucun commentaire:

Enregistrer un commentaire