入口类:
public static void main(String[] args) {
while (true) {
try {
FileClassLoader a = new FileClassLoader("E:\\workspace-nfjd\\testrealpath\\WebContent\\WEB-INF\\classes\\");
Object foo = a.findClass("Foo").newInstance();
Method m = foo.getClass().getMethod("sayHello", new Class[] {});
m.invoke(foo, new Object[] {});
} catch (Exception ex) {
ex.printStackTrace();
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
自己的类加载器:
public class FileClassLoader extends ClassLoader {
/**
* @param drive
*/
public FileClassLoader(String drive) {
super();
this.drive = drive;
}
public String drive = "E:\\workspace-nfjd\\classLoader\\bin\\";
public String fileType = ".class";
public Class findClass(String name) {
byte[] data = loadClassData(name);
return defineClass(name, data, 0, data.length);
}
public byte[] loadClassData(String name) {
FileInputStream fis = null;
byte[] data = null;
try {
fis = new FileInputStream(new File(drive + name + fileType));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int ch = 0;
while ((ch = fis.read()) != -1) {
baos.write(ch);
}
data = baos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
/**
* @param string
*/
public void setPath(String string) {
this.drive=string;
}
}
测试类:
public class Foo {
{
System.out.println("212121s111");
}
public void sayHello() {
System.out.println("hhh222");
}
}
相当于是新建了个类加载器, 内存会浪费点,不过原先的加载器会被GC掉。