ClassLoader

 

package com.jvm.seventh;

class InitalExcute{
static{
		System.out.println("init...............");
	}
}

public class InitalExcuteMain {
	
	
	public static void main(String[] args) throws ClassNotFoundException {
		//加载类 但不执行连接
		ClassLoader.getSystemClassLoader().loadClass("com.jvm.seventh.InitalExcute");
		//加载该类 进行连接 
		//JDBC驱动是通过DriverManager,必须在DriverManager中注册,
		//  如果驱动类没有被初始化,则不能注册到DriverManager中,因此必须使用forName而不能用loadClass。 
		Class.forName("com.jvm.seventh.InitalExcute");
	}
	
	
	

}

  package com.jvm.seventh;

import java.io.InputStream;

public class MyClassLoader {
	
	public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		
		ClassLoader myLoader=new ClassLoader(){
			@Override
			public Class<?> loadClass(String name){
				// TODO Auto-generated method stub
				try{
					String fileName=name.substring(name.lastIndexOf(".")+1)+".class";
					InputStream in=getClass().getResourceAsStream(fileName);
					if(in==null){
						return super.loadClass(name);
					}else{
						byte[] b=new byte[in.available()];
						in.read(b);
						return defineClass(name, b,0,b.length);
					}
				}catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
				return null;
				
			}
			
		};
		
		//自定义的classLoader
		Class clazz=myLoader.loadClass("com.jvm.seventh.MyClassLoader");
		Object obj=clazz.newInstance();
//		System.out.println(obj.getClass().getClassLoader());
		ClassLoader clo=obj.getClass().getClassLoader();
		while(clo!=null){
			System.out.println(clo);
			clo=clo.getParent();
		}
		
		//系统
		MyClassLoader cl=new MyClassLoader();
//		System.out.println(cl.getClass().getClassLoader());
		System.out.println("-----------------------------------");
		ClassLoader cloo=cl.getClass().getClassLoader();
		while(cloo!=null){
			System.out.println(cloo);
			cloo=cloo.getParent();
		}
		
		if(obj instanceof com.jvm.seventh.MyClassLoader){
			System.out.println("yes.........");
		}else{
			System.out.println("no...........");
		}
		
	}

}
 

你可能感兴趣的:(ClassLoader)