更新
这适用于 Dalvik 和 ART:new DexClassLoader(jarredDex.getAbsolutePath(), context.getDir("outdex", Context.MODE_PRIVATE).getAbsolutePath(), null, context.getClassLoader());
哪里jarredDex
是 .jar 文件classes.dex
。运行可以得到jar dx --dex --output=filename.jar your/classes/dir
。
原始答案
我从这篇文章中获取了一个代码示例。但是 ART 使用PathClassLoader
而不是 Dalvik 的DexClassLoader
. 此代码在具有 Android 6 的模拟器和具有 Android 5.1 的小米上进行了测试,并且工作正常:
// Before the secondary dex file can be processed by the DexClassLoader,
// it has to be first copied from asset resource to a storage location.
File dexInternalStoragePath = new File(getDir("dex", Context.MODE_PRIVATE), SECONDARY_DEX_NAME);
try (BufferedInputStream bis = new BufferedInputStream(getAssets().open(SECONDARY_DEX_NAME));
OutputStream dexWriter = new BufferedOutputStream(new FileOutputStream(dexInternalStoragePath))) {
byte[] buf = new byte[BUF_SIZE];
int len;
while((len = bis.read(buf, 0, BUF_SIZE)) > 0) {
dexWriter.write(buf, 0, len);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
PathClassLoader loader = new PathClassLoader(dexInternalStoragePath.getAbsolutePath(), getClassLoader());
Class<?> toasterClass = loader.loadClass("my.package.ToasterImpl");
Toaster toaster = (Toaster) toasterClass.newInstance();
toaster.show(this, "Success!");
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}