【问题标题】:Java reflection, passing a dynamically loaded interface as a parameterJava反射,将动态加载的接口作为参数传递
【发布时间】:2022-01-19 07:16:27
【问题描述】:

我遇到了一个奇怪的问题,我试图动态加载接口并将其作为参数传递给动态加载的类方法,这是在 android 上。

MyClass.java

public class MyClass{
    public interface MyInterface {
        void onSomeAction(int i,String s);
    }

    public static void setDelegate(MyInterface mInterface){
        myInterface = mInterface;
    }
    //rest of class
}

我正在尝试在下面(在另一个 java 文件中)动态访问 MyClass 和 MyInterface。

String packageName = "com.example.dynamicinterface";
PackageManager packageManager = getPackageManager();
ApplicationInfo appInfo = packageManager.getApplicationInfo(packageName, 0);
DexFile df = new DexFile(appInfo.sourceDir);
ClassLoader cl = getClassLoader();
Class myClass = df.loadClass("com.example.dynamicinterface.MyClass",cl);
Class<?> myInterface = df.loadClass("com.example.dynamicinterface.MyClass$MyInterface",cl);
Method method = myClass.getMethod("setDelegate", myInterface);
method.invoke(null,myInterface);

最后一行

method.invoke(null,myInterface);

抛出以下异常

java.lang.IllegalArgumentException:方法 com.example.dynamicinterface.MyClass.setDelegate 参数 1 的类型为 com.example.dynamicinterface.MyClass$MyInterface,得到 java.lang.Class

我被难住了。我看过几个例子,似乎都在做同样的事情。有任何想法吗?提前致谢

【问题讨论】:

  • 您正在尝试传递一个 Class 对象,该对象需要一个 MyInterface 实例。当然,这是拒绝的。你必须创建一个合适的对象,但是接口总是抽象的,所以你必须创建一个实现接口的类的实例。

标签: java android reflection


【解决方案1】:

非常感谢@Holger,我能够使用代理类解决我的问题。看看Java Reflection: Create an implementing class。我实现了一个代理实例并将其作为第二个参数传递给调用调用。

Class<?> myInterface = df.loadClass("com.example.dynamicinterface.MyClass$MyInterface",cl);

Object proxy = Proxy.newProxyInstance(myInterface.getClassLoader(),
                    new Class[] { myInterface },
                    new MyInvocationHandler());

 myClass.getMethod("setDelegate", myInterface).invoke(null,proxy);    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-21
    • 2017-10-11
    • 2016-11-22
    • 2011-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多