import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Hashtable; public class CustomClassLoader extends ClassLoader { /** * 从来存放所加载的类 */ private Hashtable<String, Class<?>> classes = new Hashtable<String, Class<?>>(); /** * 要加载文件的目录 */ private String rootDir; /** * 将此类加载器的父类设置为加载此类的类加载器 */ public CustomClassLoader(String rootDir) { super(CustomClassLoader.class.getClassLoader()); if (rootDir == null || rootDir.trim().equals("")) { throw new IllegalArgumentException("您说输入的文件目录为空"); } this.rootDir = rootDir; } /** * 根据类名加载类文件 */ public Class<?> loadClass(String className) throws ClassNotFoundException { return findClass(className); } /** * 根据类名查找类 */ public Class<?> findClass(String className) { byte classByte[]; Class<?> result = null; result = (Class<?>) classes.get(className); if (result == null) { try {//首先通过系统类加载器加载 return findSystemClass(className); } catch (Exception e) { } }else{ return result; } //通过自定义类加载器加载类文件 try { String classPath = rootDir + "\\" + className.replace('.', File.separatorChar) + ".class"; classByte = loadClassData(classPath); result = defineClass(className, classByte, 0, classByte.length, null); if(result==null){ throw new ClassNotFoundException(); } classes.put(className, result); return result; } catch (Exception e) { e.printStackTrace(); return null; } } // 负责加载class文件的数据信息 private byte[] loadClassData(String className) throws IOException { File f; f = new File(className); int size = (int) f.length(); byte buff[] = new byte[size]; FileInputStream fis = new FileInputStream(f); DataInputStream dis = new DataInputStream(fis); dis.readFully(buff); dis.close(); return buff; } }