标签:outputStream String stream UserDefineClassLoader 加载 new null 自定义
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文件所在的位置
标签:outputStream,String,stream,UserDefineClassLoader,加载,new,null,自定义 来源: https://www.cnblogs.com/LLFA/p/16390481.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。