1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| import java.io.*;
public class MyClassLoader extends ClassLoader {
private String path; private String classLoaderName;
public MyClassLoader(String path, String classLoaderName) { this.path = path; this.classLoaderName = classLoaderName; }
@Override public Class<?> findClass(String name) throws ClassNotFoundException { byte[] b = loadClassData(name); return defineClass(name, b, 0, b.length); }
public byte[] loadClassData(String name){ name = path+name+".class"; System.out.println(name); InputStream in = null; ByteArrayOutputStream out = null; try { in = new FileInputStream(new File(name)); out = new ByteArrayOutputStream(); int i = 0; while ((i = in.read()) != -1) { out.write(i); } }catch (Exception e){ e.printStackTrace();
}finally { try { out.close(); in.close(); } catch (IOException e) { e.printStackTrace(); }
} return out.toByteArray(); }
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { MyClassLoader myClassLoader = new MyClassLoader("src/main/java/", "MyClassLoader"); Class c = myClassLoader.findClass("MyClass"); System.out.println(c.getClassLoader()); System.out.println(c.getClassLoader().getParent()); System.out.println(c.getClassLoader().getParent().getParent()); c.newInstance(); } }
|