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文件。

你可能感兴趣的:(android)