检查jar冲突,查找存在相同class的jar

写在前面

本文看下如何查找jar冲突,即查找哪些jar包中存在相同的class。如果是存在相同jar的不同版本,基本一眼就能看出来,然后结合maven的依赖关系将其剔除掉即可,但是当你遇到了有人手动拷贝某些class到jar包中导致冲突的情况时,就欲哭无泪了,而我就曾掉入此🕳,灰常痛苦。所以本文就给出一段这样的程序,方便检测。

1:代码

java 复制代码
package com.dahuyou.asr.demo;

import com.sun.org.apache.xpath.internal.objects.XString;

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class scan_class {
    public static void main(String[] args) {
        String jarDirectoryPath="d:\\test\\lib";

        File directory = new File(jarDirectoryPath);
        File[] files = directory.listFiles(((dir, name) -> name.endsWith(".jar")));

        HashMap<String, String> hashMap = new HashMap<>();

        for (File jarFile : files){
            try {
                System.out.println(jarFile.getName());
                JarFile jar = new JarFile(jarFile);
                Enumeration<JarEntry> entries = jar.entries();

                while (entries.hasMoreElements()) {

                    JarEntry jarEntry = entries.nextElement();
                    String name = jarEntry.getName();

                    if (name.endsWith(".class")) {
                        String className=name.replace("/",".");

                        if(hashMap.containsKey(className)){
                            System.out.println("冲突的类:"+className);
                            System.out.println("存在于:"+hashMap.get(className)+"和:"+jarFile.getName());
                        }
                        else {
                            hashMap.put(className,jarFile.getName());
//                            System.out.println("写入:"+className+"  "+jarFile.getName());
                        }
                    }
                }

            } catch (IOException e) {
            System.err.println("无法读取 JAR 文件: " + jarFile.getName());
            e.printStackTrace();
        }

        }

    }}

测试jar,运行:

另,程序readme:

md 复制代码
功能:
检测某一路径下所有jar包的冲突类。

使用:
此处换成文件路径即可
String jarDirectoryPath="E:\\BaiduSyncdisk\\ZGM\\work\\bigdata_note\\软件安装\\seatunnel-2.3.3\\backend\\apache-seatunnel-2.3.3\\lib";

小程序,大作用!!!

写在后面

有时候,你想到了方案,却觉得麻烦而不去做,反而会导致更大的麻烦,所以,想到了就去做,工作如此,生活也亦应如此!!!

参考文章列表

相关推荐
Miketutu24 分钟前
Spring MVC消息转换器
java·spring
乔冠宇25 分钟前
Java手写简单Merkle树
java·区块链·merkle树
LUCIAZZZ1 小时前
简单的SQL语句的快速复习
java·数据库·sql
komo莫莫da2 小时前
寒假刷题Day19
java·开发语言
S-X-S3 小时前
算法总结-数组/字符串
java·数据结构·算法
linwq83 小时前
设计模式学习(二)
java·学习·设计模式
桦说编程3 小时前
CompletableFuture 超时功能有大坑!使用不当直接生产事故!
java·性能优化·函数式编程·并发编程
@_@哆啦A梦3 小时前
Redis 基础命令
java·数据库·redis
字节全栈_rJF4 小时前
性能测试 —— Tomcat监控与调优:status页监控_tomcat 自带监控
java·tomcat
爱编程的小新☆5 小时前
Java篇之继承
java·开发语言