getClassLoader()返回null,getClassLoader()获取为空

一、问题描述

通过getClassLoader()的方式获取jar包中的资源,为空:

this.getClassLoader().getResources("com/xxxx/test/Start.class").hasMoreElements();
this.getClassLoader().getResourceAsStream("test.txt");

使用ClassGraph,可以换成包名,看是否能获取到:

        try (ScanResult scanResult = new ClassGraph().acceptPackages("com.xxx.xxx.xxx").scan()) {
    
    
            scanResult.getAllResources().forEachByteArrayIgnoringIOException((io.github.classgraph.Resource res, byte[] content) -> {
    
    
                String path = res.getPath();
                System.out.println("文件:" + path);
            });
        }

二、解决方法

获取不到资源,基本上就是路径错了,或者ClassLoader不对,还有中问题就是jar包有问题,jar包中不存在目录,通过7zip可以查看:

7z l xxxx.jar

错误的jar包目录:
在这里插入图片描述
正确的jar包目录:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/mashangzhifu/article/details/123114517