有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

安卓如何在Java中使用反射调用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
    }
}

我的实施

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)

共 (2) 个答案

  1. # 1 楼答案

    您需要为下面的方法设置accessible true-

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

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

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

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

    您可以通过使用Fieldfrom Class声明来实现,如下所示:

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

    有关详细信息,请参阅here