我们为服务提供了一个基于插件的体系结构,其中我们依赖于我们支持的每个插件包。
最近,我们遇到了一个问题,在运行时我们会遇到诸如未找到枚举属性之类的错误,因为插件的枚举/类具有相同的包名称和类名称。如果插件的类/枚举具有相同的包名和类名,我们如何编写一些测试或使ANT构建失败。

最佳答案

循环访问插件目录的jar文件并查找包重复项的代码示例。

public class JarDuplicatePackageTest {
private static Map<String, Integer> packageCount = new HashMap<>();

static class JarFileFilter implements FilenameFilter {
    @Override
    public boolean accept(File dir, String name) {
        return name.endsWith("jar");
    }
}

public static void main(String[] args) {

    try {
        File pluginsDirectory = new File("plugins");
        FilenameFilter filter = new JarFileFilter();
        File[] files = pluginsDirectory.listFiles(filter);

        for(int i = 0; i < files.length; i++) {
            File file = files[i];
            FileInputStream fileInputStream = new FileInputStream(file);
            JarInputStream jarInputStream = new JarInputStream(fileInputStream);

            while(jarInputStream.getNextEntry() != null) {
                JarEntry entry = jarInputStream.getNextJarEntry();

                // list the contents of the jar file
                System.out.println(entry.toString());

                if(entry.toString().endsWith("class")) {
                    int incremented = 1;
                    if(packageCount.containsKey(entry.toString())) {
                        incremented = packageCount.get(entry.toString()) + 1;
                    }
                    packageCount.put(entry.toString(), incremented);
                }
            }
            jarInputStream.close();
            fileInputStream.close();
        }

        packageCount.forEach((k, v) -> {
            if(v > 1){ System.out.println("Duplicate: " + k );}
        });

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}


}

07-24 09:48