首页 > 解决方案 > Junit热部署无效,为什么?

问题描述

我有一个正常运行的 JUnit 程序

LauncherDiscoveryRequestBuilder builder = LauncherDiscoveryRequestBuilder.request() ;
            for (Class clazz : classes) {
                builder.selectors( selectClass( clazz  ) ) ;
            }
            LauncherDiscoveryRequest request = builder.build() ;
            launcher.execute( request ) ;

普通类加载器,没问题。

现在,我编写了一个简单的热部署并正常获取类

public class HotClassLoader extends ClassLoader {
     
    private File classPath ;

    public HotClassLoader(String path) throws IOException {
        super(ClassLoader.getSystemClassLoader()) ;
        this.classPath = new File( path ) ;
    }
    @Override
    public Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] classByte = null;
        classByte = readClassFile(name);
        if (classByte == null || classByte.length == 0) {
            throw new ClassNotFoundException("ClassNotFound : " + name);
        }
        return this.defineClass(name, classByte, 0, classByte.length);
    }
    private byte[] readClassFile(String name) throws ClassNotFoundException {
        String fileName = name.replace(".", "/") + ".class";

        File classFile = new File(this.classPath, fileName);
        if (!classFile.exists() || classFile.isDirectory()) {
            throw new ClassNotFoundException("ClassNotFound : " + name);
        }
        try(FileInputStream fis = new FileInputStream(classFile)){
            int available = fis.available();
            int bufferSize = Math.max(Math.min(1024, available), 256);
            ByteBuffer buf = ByteBuffer.allocate(bufferSize);

            byte[] bytes = null;

            FileChannel channel = fis.getChannel();
            while (channel.read(buf) > 0) {
                buf.flip();
                bytes = traslateArray(bytes, buf);
                buf.clear();
            }

            return bytes;

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public byte[] traslateArray(byte[] bytes, ByteBuffer buf) {
        if (bytes == null) {
            bytes = new byte[0];
        }
        byte[] _array = null;
        if (buf.hasArray()) {
            _array = new byte[buf.limit()];
            System.arraycopy(buf.array(), 0, _array, 0, _array.length);
        } else {
            _array = new byte[0];
        }
        byte[] _implyArray = new byte[bytes.length + _array.length];
        System.arraycopy(bytes, 0, _implyArray, 0, bytes.length);
        System.arraycopy(_array, 0, _implyArray, bytes.length,
                _array.length);
        bytes = _implyArray;
        return bytes;
    }
}

再次运行JUnit,没有反应,没有异常,什么都没有,为什么???

..................................................... .....................

JUnit 是否调用类加载器?我没有完全写 HotClassLoader。

标签: javajunit

解决方案


推荐阅读