我正在做一个项目,在这个项目中,我必须在运行时从SD卡加载一个jar文件。我已经成功地使用dexloader类实现了这一点,而且我还能够调用jar文件中带有或不带有类参数的任何函数。
现在我面临的挑战是,我必须实现一个存在于jar文件中的接口,用于项目中的回调。到目前为止,我找不到任何解决方案来实现这一点。
我以这种方式调用一个方法:
final Class[] args = new Class[1];
args[0] = Context.class;
final Method doSomething = classToLoad.getMethod("doSomething", args);
final Object myInstance = classToLoad.newInstance();
doSomething.invoke(myInstance, this);其中classLoad是从jar文件动态加载的类的实例。
任何帮助都将提前appreciated.Thanks。
发布于 2015-12-29 15:18:07
使用Proxy.newProxyInstance()创建将实现给定接口的代理对象。对接口方法的调用由您的InvocationHandler处理。示例:动态加载您的接口:
public interface SomeInterface {
void doSomething(Context context);
}创建一个实现SomeInterface的对象
Class[] ia = new Class[1];
ia[0] = Class.forName("SomeInterface");
handler = new MyHandler();
Object obj = Proxy.newProxyInstance(context.getClassLoader(),ia,handler)类MyHandler将处理对SomeInterface方法的调用:
class MyHandler implements InvocationHandler {
public Object invoke (Object proxy, Method method, Object[] args) {
if(method.getName().equals("doSomething")) {
Context context = (Context)args[0];
// do something here
}
return null;
}
}https://stackoverflow.com/questions/34505770
复制相似问题