这篇文章主要讲类加载器在android中如何动态的加载其他工程类的过程,对于类加载器的知识就跳过了。
1、首先需要创建两个工程,我创建的工程是classloader和classloaderplugin,前面的工程是主工程,后面是插件。现在classloader工程需要调用classloaderplugin插件中的类中的方法。在这里使用反射就能解决此问题。
1.1 首先看下classloaderplugin中类的方法,很简单返回两个数的和。
public class PluginClass implements Comm{
@Override
public int add(int a, int b) {
return a+b;
}
}1.2 创建类加载器和调用类里面的方法
private DexClassLoader createWrapperClassLoader(){
try {
//intent 过滤插件
Intent intent = new Intent("com.test.lb.plugin.classloaderplugin",null);
PackageManager pm = getPackageManager();
final List<ResolveInfo> plugins = pm.queryIntentActivities(intent, 0);
ResolveInfo rInfo = plugins.get(0);
ActivityInfo activityInfo = rInfo.activityInfo;
// String div = System.getProperty("path.separator");
packageName = activityInfo.packageName;
String dexPath = activityInfo.applicationInfo.sourceDir;
String dexOutputDir = getApplicationInfo().dataDir;
String libPath = activityInfo.applicationInfo.nativeLibraryDir;
return new DexClassLoader(dexPath, dexOutputDir, libPath, this.getClass().getClassLoader());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Class<?> clazz = cl.loadClass(packageName+".plugin.PluginClass");
Object obj = clazz.newInstance();
Class[] parameterTypes = new Class[2];
parameterTypes[0] = Integer.TYPE;
parameterTypes[1] = Integer.TYPE;
Method method = clazz.getMethod("add", parameterTypes);
tv_reflect_result.setText("反射调用: 20+30= "+method.invoke(obj, 20,30));原文:http://blog.csdn.net/honeybaby201314/article/details/45340023