自学内容网 自学内容网

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

写在前面

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

1:代码

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:

功能:
检测某一路径下所有jar包的冲突类。

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

小程序,大作用!!!

写在后面

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

参考文章列表


原文地址:https://blog.csdn.net/wang0907/article/details/142650932

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!