繁体   English   中英

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

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

我想使用 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)

通常,当您想使用 Java 代码访问object中声明的 object 时,您可以执行以下代码片段:

PlayerUtils.INSTANCE.setApiHelper("");
//or
PlayerUtils.INSTANCE.getApiHelper();

话虽如此,为了使用反射访问PlayerUtils中 PlayerUtils 的方法,您需要首先访问它的 static 成员,称为INSTANCE

您可以通过使用Class声明中的Field来做到这一点,如下所示:

Class<?> cls = Class.forName("reflection.PlayerUtils");
Object instance = cls.getField("INSTANCE");
Method method = cls.getDeclaredMethod("setApiHelper");
method.invoke(instance, "TESTING");

有关详细信息,请参阅此处

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