package com.popo.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class MyClassLoader extends ClassLoader {
String filePath = "D:/myclass/";
ClassLoader parent ;
public MyClassLoader(ClassLoader parent) {
// TODO Auto-generated constructor stub
this.parent=parent;
}
@Override
protected synchronized Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException {
// TODO Auto-generated method stub
Class c = null;
try {
c = findLoadedClass(name);
if (c != null)
return c;
try {
c = parent.loadClass(name);
} catch (ClassNotFoundException e) {
// TODO: handle exception
// e.printStackTrace();
}
if (c == null)
c = myFindClass(name);
return c;
} catch (Exception e) {
// TODO: handle exception
}
return super.loadClass(name, resolve);
}
private Class<?> myFindClass(String name) throws ClassNotFoundException {
String fname = name.replaceAll("\\.", "/");
System.out.println(name);
File classF = new File(filePath + fname + ".class");
try {
FileInputStream fin = new FileInputStream(classF);
try {
int len = fin.available();
byte[] b = new byte[len];
fin.read(b, 0, len);
Class<?> c = defineClass(name, b, 0, len);
fin.close();
return c;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw (new ClassNotFoundException(name + ".class not found in " + filePath));
}
return null;
}
}
测试:
先用记事本写个简单的累吧:
public class MyClass
{
public static void p(){
System.out.println("hello in MyClass loader");
}
}
手动编译下 javac MyClass.java
然后把生成的class放到D:/myclass 目录下
测试类:
package com.popo.test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MyClassLaoderTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyClassLaoderTest mct = new MyClassLaoderTest();
MyClassLoader m = new MyClassLoader( mct.getClass().getClassLoader());
try {
Class c = m.loadClass("MyClass",true);
Object o =c.newInstance();
Method method =c.getMethod("p", null);
method.invoke(o, null);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
运行结果:
MyClass
hello in MyClass loader
yeah! Succ