简体   繁体   English

如何在 Java 中使用反射调用 Kotlin object 方法?

[英]How to invoke Kotlin object method using reflection in Java?

I want to invoke setApiHelper method in the below code using java reflection.我想使用 java 反射在下面的代码中调用 setApiHelper 方法。 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:通常,当您想使用 Java 代码访问object中声明的 object 时,您可以执行以下代码片段:

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.话虽如此,为了使用反射访问PlayerUtils中 PlayerUtils 的方法,您需要首先访问它的 static 成员,称为INSTANCE

And you can do that by using Field from Class declaration, something like below:您可以通过使用Class声明中的Field来做到这一点,如下所示:

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 -您需要为以下方法设置可访问的 true -

 Class<?> cls = Class.forName("reflection.PlayerUtils");
 cls.newInstance();
 Method method = cls.getDeclaredMethod("setApiHelper");
 method.setAccessible(true);
 method.invoke(cls.newInstance(), "TESTING");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM