public class TestMyClassLoader {
static class MyClassLoader extends ClassLoader{
private String classPath;
public MyClassLoader(String classPath) {
this.classPath = classPath;
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
try{
byte[] data = loadByte(name);
return defineClass(name,data,0,data.length);
}catch (Exception e){
e.printStackTrace();
throw new ClassNotFoundException();
}
}
private byte[] loadByte(String name) throws IOException {
name = name.replaceAll("\\.","/");
FileInputStream fis = new FileInputStream(classPath + "/" + name + ".class");
int len = fis.available();
byte[] data = new byte[len];
fis.read(data);
fis.close();
return data;
}
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
MyClassLoader classLoader = new MyClassLoader("D:/test");
Class<?> clazz = classLoader.loadClass("com.zhouyu.Parent");
Object instance = clazz.newInstance();
Method method = clazz.getDeclaredMethod("test");
method.invoke(instance);
System.out.println(clazz.getClassLoader().getClass().getName());
}
}
}
自定义类加载器
最新推荐文章于 2024-11-02 15:52:57 发布