自定义加载类
public class UserDefineClassLoader extends ClassLoader{ private String rootPath; public UserDefineClassLoader(String rootPath) { this.rootPath = rootPath; } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { //转换为以文件路径表示的文件 String filePath = classToFilePath(name); //获取指定路径的class文件对应的二进制流数据 byte[] data = getByteFromPath(filePath); //自定义ClassLoader 内部调用defineClass() return defineClass(name,data,0,data.length); } private byte[] getByteFromPath(String filePath) { FileInputStream stream = null; ByteArrayOutputStream outputStream = null; try { stream = new FileInputStream(filePath); outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = stream.read(buffer)) != -1){ outputStream.write(buffer,0,len); } return outputStream.toByteArray(); }catch (Exception e){ e.printStackTrace(); }finally { try { if (stream != null){ stream.close(); } if (outputStream != null){ outputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; } private String classToFilePath(String name) { return rootPath+"\\"+name.replace(".","\\")+".class"; } public static void main(String[] args) { // E:\code\java-learn\demo\src UserDefineClassLoader classLoader = new UserDefineClassLoader("E:\\code\\java-learn\\demo\\target\\classes"); try { Class<?> aClass = classLoader.findClass("com.feng.demo.leetCode.ListDemo"); System.out.println(aClass); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
注意:
new UserDefineClassLoader()放的是class文件所在的位置
本文来自博客园,作者:金玉良猿,转载请注明原文链接:https://www.cnblogs.com/LLFA/p/16390481.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
2021-06-19 springboot和springcloud的版本问题