1 //示例: 2 package com.csair.soc; 3 4 import java.io.IOException; 5 import java.io.InputStream; 6 7 public class MyClassLoader1 extends ClassLoader{ 8 @Override 9 public Class<?> loadClass(String name) throws ClassNotFoundException{ 10 try{ 11 String fileName = name.substring(name.lastIndexOf( ".")+1) + ".class"; 12 InputStream is = this.getClass().getResourceAsStream(fileName); 13 byte[] b = new byte[is.available()]; 14 is.read(b); 15 return defineClass(name, b, 0, b.length ); 16 } catch(IOException e){ 17 throw new ClassNotFoundException(name); 18 } 19 } 20 } 21 22 23 package com.csair.soc; 24 public class ClassLoaderTest { 25 public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException { 26 MyClassLoader1 myLoader = new MyClassLoader1(); 27 Object obj = myLoader.loadClass("com.csair.soc.ClassLoaderTest" ).newInstance(); 28 System. out.println(obj.getClass()); 29 System. out.println(obj.getClass().getClassLoader()); 30 System. out.println(obj instanceof com.csair.soc.ClassLoaderTest); 31 } 32 }
1 defineClass(name, b, 0, b.length ); 2 3 ---> ClassLoader.class 4 protected final Class<?> defineClass(String name, byte[] b , int off, int len) 5 throws ClassFormatError 6 { 7 return defineClass(name, b, off, len, null); 8 } 9 10 --> 11 12 protected final Class<?> defineClass(String name, byte[] b, int off, int len, 13 ProtectionDomain protectionDomain) 14 throws ClassFormatError 15 { 16 return defineClassCond(name, b, off, len, protectionDomain, true); 17 } 18 19 ---> 20 21 private final Class<?> defineClassCond(String name, 22 byte[] b, int off, int len, 23 ProtectionDomain protectionDomain, 24 boolean verify) 25 throws ClassFormatError 26 { 27 protectionDomain = preDefineClass(name, protectionDomain); 28 29 Class c = null; 30 String source = defineClassSourceLocation(protectionDomain); 31 32 try { 33 c = defineClass1(name, b, off, len, protectionDomain, source, 34 verify); 35 } catch (ClassFormatError cfe) { 36 c = defineTransformedClass(name, b, off, len, protectionDomain, cfe, 37 source, verify); 38 }
原文:http://www.cnblogs.com/pfxiong/p/4118445.html