我目前正在开发一个分布式系统,其节点能够从服务器下载JAR和DEX文件,以在运行时更改其行为。非安卓节点使用以下代码来调用ClassLoader提供的addURL方法来添加JAR:
File f = new File(fileName);
URL u = f.toURI().toURL();
URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
Class<?> sysclass = URLClassLoader.class;
try {
Method method = sysclass.getDeclaredMethod("addURL", parameters);
method.setAccessible(true);
method.invoke(sysloader, new Object[] { u });
} catch (Throwable t) { }
在Android节点上,是否可以使用dex文件进行相同的操作?DexClassLoader和PathClassLoader没有提供addURL这样的方法。我知道可以使用反射添加单个类,但是我不知道如何添加整个dex文件。问题在于,如果我逐个添加dex中的所有类,那么由于一个类可能依赖于另一个尚未添加的类,我会收到缺少依赖项的异常。无论如何,我用来添加单个类的代码如下。
File f = new File(pathToSaveFile + dexFile);
Object obj = null;
final File optimizedDexOutputPath = context.getDir("outdex", 0);
DexClassLoader classLoader = new DexClassLoader(
f.getAbsolutePath(),
optimizedDexOutputPath.getAbsolutePath(), null,
context.getClassLoader());
String path = pathToSaveFile + dexFile;
try {
DexFile dx = DexFile.loadDex(
path,
File.createTempFile("opt", "dex", context.getCacheDir()).getPath(),
0);
Class<?> myClass = classLoader.loadClass(className);
} catch (Exception e) { }
我知道在执行动态代码卸载时存在安全问题,但这只是一个研究项目。