如我的前一篇博客一样http://blog.csdn.net/shushangxiaocao/article/details/17240889,现在来做点小优化:
原来的代码是:
比较繁琐,不熟悉反射的同学可能有点看不明白。现在,针对这部分代码,来做点有意思的优化:
首先,在Home项目中添加一个包:
里面有一个ICommon接口类,类代码如下:
public interface ICommon {
public int addOperation(int arg1,int arg2);
}
然后,将该类编译打包,编译打包命令:
执行此编译命令后,会有一个ICommon.class文件
执行此打包命令,将得到一个plugin.jar包
在Plugin中,将该jar包加上:
添加完毕后,然后AddOperation类实现ICommon:
import com.example.host.common.ICommon;
public class AddOperation implements ICommon{
@Override
public int addOperation(int arg1, int arg2) {
// TODO Auto-generated method stub
Log.i("AddOperation", "addOperation is called!");
return arg1 + arg2;
}
}
Plugin修改完毕。
Host修改,只需将文章开头的那部分代码改成下面的代码即可:
try {
Class<?> cla = dexClassLoader.loadClass(packageName + ".AddOperation");
ICommon common = (ICommon)cla.newInstance();
int result = common.addOperation(10, 30);
Log.i("Home", "result is: " + result);
} catch (Exception e){
e.printStackTrace();
}
修改完毕,运行两个app,结果如下:
学习至android的内核剖析,作者:柯元旦