标签:style blog http io ar color os 使用 sp
java.lang.ClassLoader
。protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { // First, check if the class has already been loaded Class c = findLoadedClass(name); if (c == null) { 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. c = findClass(name); } } if (resolve) { resolveClass(c); } return c; }
1 package com.csair.soc.thread; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 6 public class MyClassLoader extends ClassLoader{ 7 @Override 8 public Class<?> loadClass(String name) throws ClassNotFoundException { 9 try { 10 String fileName = name.substring(name.lastIndexOf("." ) + 1) 11 + ".class"; 12 InputStream is = this.getClass().getResourceAsStream(fileName); 13 if (is == null) { 14 return super.loadClass(name); 15 } 16 byte[] b = new byte[is.available()]; 17 is.read(b); 18 return defineClass(name, b, 0, b. length); 19 } catch (IOException e) { 20 throw new ClassNotFoundException(name); 21 } 22 } 23 }
1 package com.csair.soc.thread; 2 3 public class ThreadContextTest { 4 public static void main(String[] args) throws ClassNotFoundException { 5 ThreadTest tt = new ThreadTest(); 6 //设置线程的上下文类加载器 7 tt.setContextClassLoader( new com.csair.soc.thread.MyClassLoader()); 8 tt.start(); 9 } 10 public static class ThreadTest extends Thread{ 11 public void run() { 12 try { 13 System. out.println( "线程上下文类加载器:" + getContextClassLoader()); 14 System. out.println( "当前类加载器:" +this.getClass().getClassLoader()); 15 Class<?> class1 = getContextClassLoader().loadClass("com.csair.soc.thread.ThreadContextTest" ); 16 System. out.println( "加载class的类加载器:" +class1.getClassLoader()); 17 } catch (ClassNotFoundException e) { 18 e.printStackTrace(); 19 } 20 } 21 } 22 }
标签:style blog http io ar color os 使用 sp
原文地址:http://www.cnblogs.com/pfxiong/p/4118436.html