實現自定義類加載器的三步:java
一個基本的自定義類加載器代碼以下:ide
package cn.xpleaf.coding.c4; import java.io.*; /** * @author xpleaf * @date 2019/3/10 11:10 AM */ public class CustomClassLoader extends ClassLoader { @Override protected Class<?> findClass(String name) throws ClassNotFoundException { try { byte[] result = getClassFromCustomPath(name); if (result == null) { throw new FileNotFoundException(name); } else { // defineClass方法將字節碼轉化爲類 return defineClass(name, result, 0, result.length); } } catch (Exception e) { e.printStackTrace(); } throw new ClassNotFoundException(name); } private byte[] getClassFromCustomPath(String name) { // 從自定義路徑中加載指定類,返回類的字節碼文件 InputStream in = null; ByteArrayOutputStream out = null; String path = "/Users/yeyonghao/" + name + ".class"; try { in = new FileInputStream(path); out = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int len = 0; while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } return out.toByteArray(); } catch (Exception e) { e.printStackTrace(); } finally { try { in.close(); out.close(); } catch (Exception e) { e.printStackTrace(); } } return null; } public static void main(String[] args) { CustomClassLoader customClassLoader = new CustomClassLoader(); try { Class<?> clazz = Class.forName("One", true, customClassLoader); Object obj = clazz.newInstance(); // cn.xpleaf.coding.c4.CustomClassLoader@610455d6 System.out.println(obj.getClass().getClassLoader()); } catch (Exception e) { e.printStackTrace(); } } }
執行結果以下:code
cn.xpleaf.coding.c4.CustomClassLoader@610455d6