DexClassLoader和PathClassLoder

DexClassLoder和PathClassLoader都继承自BaseDexClassLoader,唯一的区别就是传入super构造方法的optimizedDirectory参数,前者可以在外部传入,后者不可以在外部调用时传入,而自己默认传入了null。

一个有值一个为null,这个影响了后面加载dex或jar/apk/zip文件时的决策,BaseDexClassLoader使用DexPathList类去加载,DexPathList中按照是否后缀为.dex做一次决策,然后optimizedDirectory是否为null再做决策,如下代码:

private static DexFile loadDexFile(File file, File optimizedDirectory)
        throws IOException {
    if (optimizedDirectory == null) {
        return new DexFile(file);
    } else {
        String optimizedPath = optimizedPathFor(file, optimizedDirectory);
        return DexFile.loadDex(file.getPath(), optimizedPath, 0);
    }
}

然后都调用到了native代码中,不再细追,总之按照官网说的:

DexClassLoader:

A class loader that loads classes from .jar and .apk files containing a classes.dex entry. This can be used to execute code not installed as part of an application.

This class loader requires an application-private, writable directory to cache optimized classes. Use Context.getCodeCacheDir() to create such a directory:

File dexOutputDir = context.getCodeCacheDir();

Do not cache optimized classes on external storage. External storage does not provide access controls necessary to protect your application from code injection attacks.

PathClassLoader:

Provides a simple ClassLoader implementation that operates on a list of files and directories in the local file system, but does not attempt to load classes from the network. Android uses this class for its system class loader and for its application class loader(s).

这两个规矩的用法就是上面的说法,但是可以根据自己的不同需求进行灵活运用。如果都是加载内部存储的dex文件,这两个应该没什么区别。但是只有DL可以加载外部存储的dex/zip/apk/jar文件。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值