java 类加载的一些理解

首先类加载过程的确是使用双亲委托方式,就是先找parent的classLoader加载,java有几个固定的classLoader:1、BootstrapClassLoader 2、ExtClassLoader 3、AppClassLoader 这里有篇文章,也讲些了这些classLoader的关系 加载器

但是网上很多文章说这几个加载器是有继承关系,然后我看到代码它们是没有继承关系的,但是它们都有个getParent()方法去获取所谓的父加载器,其实这个值的设置就要看Launcher的代码

public class Launcher {
	private static URLStreamHandlerFactory factory = new Factory();
	private static Launcher launcher = new Launcher();

	public static Launcher getLauncher() {
		return launcher;
	}

	private ClassLoader loader;

	// ClassLoader.getSystemClassLoader会调用此方法
	public ClassLoader getClassLoader() {
		return loader;
	}

	public Launcher() {
		// 1. 创建ExtClassLoader
		ClassLoader extcl;
		try {
			extcl = ExtClassLoader.getExtClassLoader();
		} catch (IOException e) {
			throw new InternalError("Could not create extension class loader");
		}

		// 2. 用ExtClassLoader作为parent去创建AppClassLoader
		try {
			loader = AppClassLoader.getAppClassLoader(extcl);
		} catch (IOException e) {
			throw new InternalError("Could not create application class loader");
		}

		// 3. 设置AppClassLoader为ContextClassLoader
		Thread.currentThread().setContextClassLoader(loader);
		// ...
	}

	static class ExtClassLoader extends URLClassLoader {
		private File[] dirs;

		public static ExtClassLoader getExtClassLoader() throws IOException {
			final File[] dirs = getExtDirs();
			return new ExtClassLoader(dirs);
		}

		public ExtClassLoader(File[] dirs) throws IOException {
			super(getExtURLs(dirs), null, factory);
			this.dirs = dirs;
		}

		private static File[] getExtDirs() {
			String s = System.getProperty("java.ext.dirs");
			File[] dirs;
			// ...
			return dirs;
		}
	}

	/**
	 * The class loader used for loading from java.class.path. runs in a
	 * restricted security context.
	 */
	static class AppClassLoader extends URLClassLoader {

		public static ClassLoader getAppClassLoader(final ClassLoader extcl) throws IOException {
			final String s = System.getProperty("java.class.path");
			final File[] path = (s == null) ? new File[0] : getClassPath(s);

			URL[] urls = (s == null) ? new URL[0] : pathToURLs(path);
			return new AppClassLoader(urls, extcl);
		}

		AppClassLoader(URL[] urls, ClassLoader parent) {
			super(urls, parent, factory);
		}

		/**
		 * Override loadClass so we can checkPackageAccess.
		 * 这个方法似乎没什么必要,因为super.loadClass(name, resolve)时也会checkPackageAccess
		 */
		public synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException {
			int i = name.lastIndexOf('.');
			if (i != -1) {
				SecurityManager sm = System.getSecurityManager();
				if (sm != null) {
					//
					sm.checkPackageAccess(name.substring(0, i));
				}
			}
			return (super.loadClass(name, resolve));
		}

	}
}

  1. Launcher源码里定义了static的扩展类加载器ExtClassLoader, static的系统类加载器AppClassLoader。
  2. 它们都是默认包级别的,它们都是继承URLClassLoader,这就意味着我们的代码里,不能定义ExtClassLoader laoder = ...或AppClassLoader loader = ...。我们只能ClassLoader loader = ...,而在实际运行时,我们应当能辨别这个loader到底是哪个具体类型。
  3. 在ExtClassLoader构造器里,并没有指定parent,或者说ExtClassLoader的parent为null。因为ExtClassLoader的parent是BootstrapLoader,而BootstrapLoader不存在于Java Api里,只存在于JVM里,我们是看不到的,所以请正确理解"ExtClassLoader的parent为null"的含义。
  4. 在AppClassLoader构造器里,有了parent。实例化AppClassLoader的时候,传入的parent就是一个ExtClassLoader实例。
  5. 看看Launcher的构造方法。
    1. 先实例化ExtClassLoader,从java.ext.dirs系统变量里获得URL[]。
    2. 用这个ExtClassLoader作为parent去实例化AppClassLoader,从java.class.path系统变量里获得URL[]。Launcher getClassLoader()就是返回的这个AppClassLoader。
    3. 设置AppClassLoader为ContextClassLoader。

到这里,关键是我们是怎么使用这个Launcher的,可以看看ClassLoader的代码,在构造函数中

    protected ClassLoader() {
        this(checkCreateClassLoader(), getSystemClassLoader());
    }
    @CallerSensitive
    public static ClassLoader getSystemClassLoader() {
        initSystemClassLoader();
        if (scl == null) {
            return null;
        }
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            checkClassLoaderPermission(scl, Reflection.getCallerClass());
        }
        return scl;
    }
    private static synchronized void initSystemClassLoader() {
        if (!sclSet) {
            if (scl != null)
                throw new IllegalStateException("recursive invocation");
            sun.misc.Launcher l = sun.misc.Launcher.getLauncher();
            if (l != null) {
                Throwable oops = null;
                scl = l.getClassLoader();
                try {
                    scl = AccessController.doPrivileged(
                        new SystemClassLoaderAction(scl));
                } catch (PrivilegedActionException pae) {
                    oops = pae.getCause();
                    if (oops instanceof InvocationTargetException) {
                        oops = oops.getCause();
                    }
                }
                if (oops != null) {
                    if (oops instanceof Error) {
                        throw (Error) oops;
                    } else {
                        // wrap the exception
                        throw new Error(oops);
                    }
                }
            }
            sclSet = true;
        }
    }

sun.misc.Launcher l = sun.misc.Launcher.getLauncher(); 就在这里使用,但是当我new 一个自定义classLoader的时候,其实这个scl变量已经存在值,这是因为这个是静态变量,在我调用之前已经有别的类调用过了,因此这里有值。

下面是一些练习出现的情况:

出现以下异常:

Exception in thread "main" java.lang.ClassCastException: com.cong.ClassLoaderLK cannot be cast to com.cong.ClassLoaderLK
看起来两个对象一样,为什么不能转换呢,因为加载的时候我把双亲委派的方式破坏了,其实这个两个类是不同的class实例化出来的,虽然是同一份字节文件,但是用了两个不同的classloader来加载就会出现这个问题

我的练习代码:

package com.cong;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;



public class ClassLoaderLK extends ClassLoader {
    /**
     * @param args
     */
    public static void main(String[] args) {
//        this.class.getSystemClassLoader();
        
        String ext = "java.ext.dirs";
        System.out.println("java.ext.dirs :\n" + System.getProperty(ext));
        String cp = "java.class.path";
        System.out.println("java.class.path :\n" + System.getProperty(cp));
        
        ClassLoader currentClassloader = ClassLoaderLK.class.getClassLoader();
        ClassLoader c = sun.misc.Launcher.class.getClassLoader();
        System.out.println(c);
        c = System.class.getClassLoader();
        System.out.println(c);
        c = AbcBean.class.getClassLoader();
        System.out.println(c);
        //sun.misc.Launcher$ExtClassLoader@2259e205
        
        //这个地址是你的classpath
        String pp = "E:\\demo\\用 SpringMVC+MyBatis 来搭建网站\\源码\\demo\\target\\classes\\";
        ClassLoaderLK cl = new ClassLoaderLK(currentClassloader, pp);
        
        System.out.println();
        System.out.println("currentClassloader is " + currentClassloader);
        System.out.println();
       String name = "com.cong.AbcBean.class";
       // String name = "java.util.Arrays.class";
       
        name = "com.cong.AbcBean";
        
        String name2 = "com.cong.ClassLoaderLK";
       // name = "java.util.Arrays";
        try {
            //Class<?> loadClass = cl.loadClass(name);
        	AbcBean abc = new AbcBean();
        	AbcBean abc2 = new AbcBean();
        	abc.greeting();
        	
        	//System.out.println(abc.greeting());
        	//Class<?> loadClass = cl.findClass(name);
        	Class<?> loadClass = cl.findClass(name);
        	System.out.println(loadClass.getClassLoader());
        	Class<?> loadClass2 = cl.findClass(name2);
        	 Constructor ccc =loadClass2.getDeclaredConstructor(new Class[]{String.class});
        	
        	System.out.println(ccc.newInstance(new Object[]{pp}).getClass().getClassLoader());
        	Object o = ccc.newInstance(new Object[]{pp});
        	System.out.println(o.getClass().getClassLoader());
        	Method m = o.getClass().getMethod("findClass", String.class);
        	Object oo =  m.invoke(o, name);
        	System.out.println(oo.getClass().getClassLoader());//这里不明白为什么为null
        	System.out.println(oo.getClass().getClassLoader().getParent());
        	// ll.getClass().getClassLoader()
        //	ClassLoaderLK ll =  (ClassLoaderLK)loadClass2.newInstance();
        	//Class<?> loadClass2 = cl.findClass(name);
        	//loadClass = ll.findClass(name);
        	//System.out.println("===" + (loadClass == loadClass2));
            
            Object object = loadClass.newInstance();
            
            System.out.println(object.getClass().getClassLoader());
            System.out.println(object.getClass().getClassLoader().getParent());
            System.out.println(object.getClass().getClassLoader().getParent().getParent());
            System.out.println("abc==abc2" + (abc.getClass() == abc2.getClass()));
            System.out.println("abc==object" + (abc.getClass() == object.getClass()));
            System.out.println("abcClassLoader=" + abc.getClass().getClassLoader());
            System.out.println("objectClassLoader=" + object.getClass().getClassLoader());
         //  URLClassLoader
            System.out.println("123=" + object.getClass());
//            AbcBean ss = (AbcBean) object; // 无法转换的 (1)
//            ss.greeting();  (1)
            
            System.out.println();
            System.out.println(" invoke some method !");
            System.out.println();
            
            Method method = loadClass.getMethod("greeting");
            method.invoke(object);
            
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    
    private ClassLoader parent = null; // parent classloader
    private String path;

    public ClassLoaderLK(ClassLoader parent, String path) {
      //  super(parent);
      //  this.parent = parent; // 这样做其实是无用的
        this.path = path;
    }

    public ClassLoaderLK(String path) {
        this.path = path;
    }
    
    //实现了双亲委派
    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
//        return super.loadClass(name);
        Class<?> cls = findLoadedClass(name);//主要是检查类是否有加载过
        if (cls == null) {
//            cls = getSystemClassLoader().loadClass(name); (2)// SystemClassLoader 会从classpath下加载
//            if (cls == null) {(2)
            // 默认情况下, 当前cl的parent是 SystemClassLoader, 
            // 而当前cl的parent的parent 才是ExtClassLoader
        	     ClassLoader parent1 = getParent();
                ClassLoader parent2 = parent1.getParent();
//                System.out.println("Classloader is : " + parent2); 
                //使用父classload 就是appClassLoad
                try {
                    System.out.println("try to use APPClassLoader to load class : " + name); 
                    cls = parent1.loadClass(name);
                } catch (ClassNotFoundException e) {
                    System.out.println("APPClassLoader.loadClass :" + name + " Failed"); 
                }
                
                //这里是使用extClassLoader加载
        /*        try {
                    System.out.println("try to use ExtClassLoader to load class : " + name); 
                    cls = parent2.loadClass(name);
                } catch (ClassNotFoundException e) {
                    System.out.println("ExtClassLoader.loadClass :" + name + " Failed"); 
                }*/
//            }(2)
            
            if (cls == null) {
                System.out.println("try to ClassLoaderLK load class : " + name); 
                cls = findClass(name);
                
                if (cls == null) {
                    System.out.println("ClassLoaderLK.loadClass :" + name + " Failed"); 
                } else {
                    System.out.println("ClassLoaderLK.loadClass :" + name + " Successful"); 
                }
                
            } else {
                System.out.println("ExtClassLoader.loadClass :" + name + " Successful"); 
            }
        }
        return cls;
    }
    
    //没有实现双亲委派
    @Override
    @SuppressWarnings("rawtypes")
    public Class<?> findClass(String name) throws ClassNotFoundException {
//        return super.findClass(name);
        System.out.println( "try findClass " + name);
        InputStream is = null;
        Class class1 = null;
        try {
            String classPath = name.replace(".", "\\") + ".class";
//            String[] fqnArr = name.split("\\."); // split("."); 是不行的, 必须split("\\.")
//            if (fqnArr == null || fqnArr.length == 0) {
//                System.out.println("ClassLoaderLK.findClass()");
//                fqnArr = name.split("\\.");
//            } else {
//                System.out.println( name  +  fqnArr.length);
//            }
            
            String classFile = path + classPath;
            byte[] data = getClassFileBytes(classFile );
            
            class1 = defineClass(name, data, 0, data.length);
            if (class1 == null) {
                System.out.println("ClassLoaderLK.findClass() ERR ");
                throw new ClassFormatError();
            }
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return class1;
    }

    private byte[] getClassFileBytes(String classFile) throws Exception {
        FileInputStream fis = new FileInputStream(classFile );
        FileChannel fileC = fis.getChannel();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        WritableByteChannel outC = Channels.newChannel(baos);
        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
        while (true) {
            int i = fileC.read(buffer);
            if (i == 0 || i == -1) {
                break;
            }
            buffer.flip();
            outC.write(buffer);
            buffer.clear();
        }
        fis.close();
        return baos.toByteArray();
    }
    
}

package com.cong;

import java.util.Date;


public class AbcBean {
    
    @Override
    public String toString() {
        return "AbcBean [name=" + name + ", age=" + age + "]";
    }
    
    String name;
    int age;
    Date birthDay;
    
    public Date getBirthDay() {
        return birthDay;
    }
    public void setBirthDay(Date birthDay) {
        this.birthDay = birthDay;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
    public void greeting() {
        System.out.println("AbcBean.greeting()");
    }
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值