[英]Java reflection, passing a dynamically loaded interface as a parameter
我有一個奇怪的問題,我試圖動態加載接口並將其作為參數傳遞給動態加載的 class 方法,這是在 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
}
我正在嘗試在下面動態訪問 MyClass 和 MyInterface(在另一個 java 文件中)。
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: method com.example.dynamicinterface.MyClass.setDelegate argument 1 has type com.example.dynamicinterface.MyClass$MyInterface, got java.lang.Class<com.example.dynamicinterface.MyClass$MyInterface>
我難住了。 我看過幾個例子,似乎都在做同樣的事情。 有任何想法嗎? 提前致謝
非常感謝@Holger,我能夠使用代理 class 解決我的問題。 看看Java 反思:創建一個實施 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.