有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

类加载器锁定的Java JAR文件

我正在临时文件夹中提取WAR,并将所有类和库添加到URLClassLoader

当我开始将类加载到类路径中时,“WEB-INF/lib/”下的JAR文件被JVM锁定

完成这项工作后,我关闭类路径,调用GC并删除临时目录

当我删除临时目录时,我可以删除除“WEB-INF/lib”下的JAR文件之外的所有文件

我的代码:

@Override
public void generateRegressionTestClasses(Path fileJARorWarSolution, List<String> canonicalNameClassesToGenerateTests) throws Exception {

    Path tempPath = null;
    URLClassLoader classLoader = null;
    TryTest tryTest = null;
    RDP execution = null;
    try {
        // This extracts the JAR/WAR and prepares the URLClassLoader.
        GenFilterResponse response = genFilterClass.runGenFilterClass(path);

        classLoader = response.getCl();
        tempPath = response.getTempPath();

        // Verify that all the Test classes is in the ClassLoader.
        // Here is where the JAR files are locked.
        for (String s : canonicalNameClassesToGenerateTests) {
            try {
                classLoader.loadClass(s);
            } catch (ClassNotFoundException e) {
                throw new CustomException(CustomTexts.ERROR_CLASS_NOT_LOADED + s);
            }
        }

        execution = new RDP();
        execution.setClassLoader(classLoader);

        TryTest = new TryTest(execution);
        tryTest.handle(null);
    } finally {
        tryTest = null;
        execution = null;
        if (classLoader != null) {
            try {
                classLoader.close();
            } catch (Exception e) {
                //
            } finally {
                classLoader = null;
                System.gc();
            }
        }
        if (tempPath != null) {
            FileSystemUtils.deleteRecursively(tempPath.toFile());
        }
    }

有人知道如何解锁这些文件吗


共 (1) 个答案

  1. # 1 楼答案

    解决了

    如果我使用这种URI将JAR加载到类加载器中:

    new URL("jar:file:" + jar.toAbsolutePath().toString() + "!/").toURI().toURL()
    

    示例URI:

    jar:file:c:/myJar。罐子

    类加载器关闭后,文件被锁定

    如果我使用这种URI将JAR加载到类加载器中:

    warDirectory.toFile().toURI().toURL()
    

    示例URI:

    文件:c:/myJar。罐子

    我可以在类加载器关闭时删除JAR