检查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";

小程序,大作用!!!

写在后面

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

参考文章列表

相关推荐
IKUN家族1 小时前
Spring IoC&DI
java·spring·rpc
山荷枝3 小时前
03-框架--Spring
java·后端·spring
ChaHae-In3 小时前
SpringBoot统一功能处理
java·spring boot·后端
coder!mq4 小时前
说几个常见的语法糖?
java·开发语言·算法
gugucoding4 小时前
38. 【Java】Stream API(下):高级操作与性能
java·开发语言
心平气和量大福大4 小时前
android-实例-蒲公英-更新与安装-5-签名与生成APK
android·java·开发语言
952365 小时前
Spring-cloud配置中心
java·spring·spring cloud·微服务
ydd1001005 小时前
寻找两个正序数组的中位数 Java 题解,二分分割详解
java·开发语言
真上帝的左手6 小时前
10. 软件设计&架构-Spring Security 7 整合CAS SSO 单点登录
java·spring·架构·sso
Zane19947 小时前
单例线程安全、生产者消费者、死锁:并发面试三连问串讲
java·后端