Android开发Android开发经验谈Java 杂谈

Java ClassLoader类加载机制(二)类加载器

2019-04-29  本文已影响4人  魏树鑫

1. 类加载的种类

程序加载入口sun.misc.Launcher

package sun.misc;                                                                
                                              
/**                                                                              
 * This class is used by the system to launch the main application.              
 */                                                                              
public class Launcher {                                                          
    private static URLStreamHandlerFactory factory = new Factory();              
    private static Launcher launcher = new Launcher();                           
    private static String bootClassPath = System.getProperty("sun.boot.class.path");                               
                                                                                 
    public static Launcher getLauncher() {                                       
        return launcher;                                                         
    }                                                                            
                                                                                 
    private ClassLoader loader;                                                  
                                                                                 
    public Launcher() {                                                          
        // Create the extension class loader                                     
        ClassLoader extcl;                                                       
        try {                                                                    
            extcl = ExtClassLoader.getExtClassLoader();                          
        } catch (IOException e) {                                                
            throw new InternalError("Could not create extension class loader", e);                   
        }                                                                        
        // Now create the class loader to use to launch the application          
        try {                                                                    
            loader = AppClassLoader.getAppClassLoader(extcl);                    
        } catch (IOException e) {                                                
            throw new InternalError("Could not create application class loader", e);                 
        }                                                                        
        // Also set the context class loader for the primordial thread.          
        Thread.currentThread().setContextClassLoader(loader);                    
        // Finally, install a security manager if requested                      
        String s = System.getProperty("java.security.manager");                  
        if (s != null) {                                                         
            SecurityManager sm = null;                                           
            if ("".equals(s) || "default".equals(s)) {                           
                sm = new java.lang.SecurityManager();                            
            } else {                                                             
                try {                                                            
                    sm = (SecurityManager)loader.loadClass(s).newInstance();     
                } catch (IllegalAccessException e) {                             
                } catch (InstantiationException e) {                             
                } catch (ClassNotFoundException e) {                             
                } catch (ClassCastException e) {                                 
                }                                                                
            }                                                                    
            if (sm != null) {                                                    
                System.setSecurityManager(sm);                                   
            } else {                                                             
                throw new InternalError("Could not create SecurityManager: " + s);                   
            }                                                                    
        }                                                                        
    }
}

可以发现

  1. 系统先拿个扩展类加载器ExtClassLoader.getExtClassLoader(),然后又拿个应用加载器AppClassLoader.getAppClassLoader(extcl),并且将ExtClassLoader设为AppClassLoader的父加载器;
  2. 设置当前线程的ClassLoader,也就是说,系统的第一个线程的类加载器都由AppClassLoader来加载;
  3. 最后再初始化个安全策略的Manager,用于在执行不安全或者敏感的操作时,进行安全校验;比如文件权限校验;
    看一下Launcher中的各个类的关系:


    Launcher与ClassLoader关系.png

可以发现所有的类加载器最终都是继承自ClassLoader,而AppClassLoader和ExClassLoader是Launcher的内部类。

2. 真正开始加载类,loaderClass方法

 protected Class<?> loadClass(String name, boolean resolve)
        throws ClassNotFoundException
    {
        synchronized (getClassLoadingLock(name)) {
            // First, check if the class has already been loaded
            Class<?> c = findLoadedClass(name);
            if (c == null) {
                long t0 = System.nanoTime();
                try {
                    if (parent != null) {
                        c = parent.loadClass(name, false);
                    } else {
                        c = findBootstrapClassOrNull(name);
                    }
                } catch (ClassNotFoundException e) {
                    // ClassNotFoundException thrown if class not found
                    // from the non-null parent class loader
                }

                if (c == null) {
                    // If still not found, then invoke findClass in order
                    // to find the class.
                    long t1 = System.nanoTime();
                    c = findClass(name);

                    // this is the defining class loader; record the stats
                    sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);
                    sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
                    sun.misc.PerfCounter.getFindClasses().increment();
                }
            }
            if (resolve) {
                resolveClass(c);
            }
            return c;
        }
    }

双亲委派模型

双亲委派好处

3. 自定义ClassLoader

 class NetworkClassLoader extends ClassLoader {
     String host;
     int port;
     public Class findClass(String name) {
         byte[] b = loadClassData(name);
         return defineClass(name, b, 0, b.length);
     }
     private byte[] loadClassData(String name) {
         // load the class data from the connection
     }
 }

4. 类加载决定对象是否相同

要判断两个类是否“相同”,前提是这两个类必须被同一个类加载器加载,否则这个两个类不“相同”。

这里指的“相同”,包括类的Class对象的equals()方法、isAssignableFrom()方法、isInstance()方法、instanceof关键字等判断出来的结果

public class ClassLoaderTest {

    public static void main(String[] args) {
        ClassLoader newClassLoader = new ClassLoader() {
            @Override
            public Class<?> loadClass(String name) throws ClassNotFoundException {
                try {
                    String fileName = name.substring(name.lastIndexOf(".") + 1) + ".class";
                    InputStream resourceAsStream = getClass().getResourceAsStream(fileName);
                    if (resourceAsStream == null) {
                        return super.loadClass(name);
                    }
                    byte[] bytes = new byte[resourceAsStream.available()];
                    int read = resourceAsStream.read(bytes);
                    resourceAsStream.close();
                    return defineClass(name, bytes, 0, read);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return super.loadClass(name);
            }
        };

        ClassLoader appClassLoader = ClassLoader.getSystemClassLoader();

        ClassLoader parentClassLoader = ClassLoaderTest.class.getClassLoader().getParent();

        try {
            String className = "com.wei.sample.classloader.ClassLoaderTest";
            Class<?> aClass = newClassLoader.loadClass(className);
            System.out.println(aClass);
            System.out.println(aClass.newInstance() instanceof com.wei.sample.classloader.ClassLoaderTest);
            System.out.println(ClassLoaderTest.class.getClassLoader().loadClass(className).newInstance() instanceof com.wei.sample.classloader.ClassLoaderTest);
            System.out.println(appClassLoader.loadClass(className).newInstance() instanceof com.wei.sample.classloader.ClassLoaderTest);
        } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
            e.printStackTrace();
        }
    }
}

//Console 输出
[Loaded com.wei.sample.classloader.ClassLoaderTest from file:../compileDebugJavaWithJavac/classes/]
[Loaded com.wei.sample.classloader.ClassLoaderTest$1 from file:../compileDebugJavaWithJavac/classes/]
[Loaded com.wei.sample.classloader.ClassLoaderTest from __JVM_DefineClass__]

class com.wei.sample.classloader.ClassLoaderTest
false
true
true

上一篇下一篇

猜你喜欢

热点阅读