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());
}
}
}
自定义类加载器
最新推荐文章于 2025-11-24 14:38:27 发布
本文介绍了如何在Java中创建一个自定义的ClassLoader,通过`MyClassLoader`实现按指定路径加载`com.zhouyu.Parent`类并调用其方法。
1065

被折叠的 条评论
为什么被折叠?



