|
| 1 | +package com.zyj.test; |
| 2 | + |
| 3 | +import java.io.*; |
| 4 | + |
| 5 | +/** |
| 6 | + * 版权声明:CopyRight (c) 2018 ucarinc. All Rights Reserved. |
| 7 | + * |
| 8 | + * @author : 张勇杰 |
| 9 | + * @date : 2018/12/6 14:47 |
| 10 | + * @Version : v1.0 |
| 11 | + * @description |
| 12 | + **/ |
| 13 | +public class FileSystemClassLoader extends ClassLoader { |
| 14 | + //d:/myjava/com/zyj/test/User.class -->com.zyj.test.User |
| 15 | + private String rootDir; |
| 16 | + |
| 17 | + public FileSystemClassLoader(String rootDir){ |
| 18 | + this.rootDir = rootDir; |
| 19 | + } |
| 20 | + |
| 21 | + @Override |
| 22 | + protected Class<?> findClass(String name) throws ClassNotFoundException { |
| 23 | + Class<?> c = findLoadedClass(name); |
| 24 | + |
| 25 | + //应该先查询有没有加载过这个类,如果已经加载,则返回已经加载好的类。如果没有,则加载新的类 |
| 26 | + if(c != null){ |
| 27 | + return c; |
| 28 | + }else{ |
| 29 | + ClassLoader parent = this.getParent(); |
| 30 | + System.out.println(parent); |
| 31 | + //委派给父类加载 |
| 32 | + try { |
| 33 | + c = parent.loadClass(name); |
| 34 | + }catch (Exception e){ |
| 35 | + |
| 36 | + } |
| 37 | + |
| 38 | + if(c != null){ |
| 39 | + return c; |
| 40 | + }else{ |
| 41 | + byte[] classData = getClassData(name); |
| 42 | + if(classData == null){ |
| 43 | + throw new ClassNotFoundException(); |
| 44 | + }else{ |
| 45 | + c = defineClass(name,classData,0,classData.length); |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + return c; |
| 50 | + } |
| 51 | + |
| 52 | + private byte[] getClassData(String className){ |
| 53 | + String path = rootDir + "/"+className.replace(".","/")+".class"; |
| 54 | + |
| 55 | + //IOUtils,可以使用他将流中的数据转成字节数组 |
| 56 | + InputStream is = null; |
| 57 | + ByteArrayOutputStream baos = new ByteArrayOutputStream(); |
| 58 | + try { |
| 59 | + is = new FileInputStream(path); |
| 60 | + byte[] buffer = new byte[1024]; |
| 61 | + int temp = 0; |
| 62 | + while((temp = is.read(buffer))!= -1){ |
| 63 | + baos.write(buffer,0,temp); |
| 64 | + } |
| 65 | + return baos.toByteArray(); |
| 66 | + } catch (Exception e) { |
| 67 | + e.printStackTrace(); |
| 68 | + return null; |
| 69 | + }finally { |
| 70 | + if(is != null){ |
| 71 | + try { |
| 72 | + is.close(); |
| 73 | + } catch (IOException e) { |
| 74 | + e.printStackTrace(); |
| 75 | + } |
| 76 | + } |
| 77 | + if (baos != null) { |
| 78 | + |
| 79 | + try { |
| 80 | + baos.close(); |
| 81 | + } catch (IOException e) { |
| 82 | + e.printStackTrace(); |
| 83 | + } |
| 84 | + } |
| 85 | + } |
| 86 | + } |
| 87 | +} |
0 commit comments