【问题标题】:Howto correctly add compiled class files to jar with package structure如何正确地将已编译的类文件添加到具有包结构的 jar 中
【发布时间】:2016-01-25 16:13:02
【问题描述】:

我有一个生成源代码的程序,并希望在 java 运行时执行期间编译此源代码,例如:

generateSource()
compileSource()

我使用 ToolProvider 的 JavaCompiler:

ArrayList<String> optionList = new ArrayList<String>();
System.out.println("Retrieve dependendcy Jars");
ArrayList<File> jarfiles = getJarFiles(this.libdir);
String libpath = System.getProperty("java.class.path") + convertJarFilesToClassPath(jarfiles);
optionList.addAll(Arrays.asList("-d", this.genClassDir ));
optionList.addAll(Arrays.asList("-classpath", libpath));

ArrayList<File> files1 =  getSourceFiles(this.genCodeDir); 
Iterable<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjectsFromFiles(files1);
JavaCompiler.CompilationTask task = compiler.getTask(null ,fileManager , null, optionList, null, compilationUnits1 );
task.call();

现在重要的一行是我在选项列表中添加 -d 类目录的位置。

我有这个 genClassDir /gen/classes 我所有的 .class 文件都在里面,包括子目录。

现在我的 jar 文件中的问题是,类文件在包结构之前具有 genClassDir 作为前缀。

./gen/classes/foo/
./gen/classes/foo/bar/

而不是

/foo
/foo/bar

或没有前导斜杠。

我正在包装罐子,就像How to use JarOutputStream to create a JAR file? 的第一个答案一样

有没有办法只获取 jar 中类文件的包结构?

【问题讨论】:

    标签: java jar java-compiler-api javacompiler


    【解决方案1】:

    您可以将basePath 参数添加到另一个问题中显示的解决方案的add() 方法中,并在创建Jarentry 之前从每个文件名中删除基本路径

    private void add(File source, String basePath, JarOutputStream target) throws IOException
    {
        //...
        name = name.replaceFirst(basePath, "");
        JarEntry entry = new JarEntry(name);
        //...
    }
    

    根据需要调整替换(前导/尾随斜杠、反斜杠代替斜杠等)

    用法:

    add(new File("gen/classes/test.class", "gen/classes", new JarOutputStream(...));
    

    【讨论】:

    • 我在考虑这个问题,但是JarEntries 还能找到吗?
    • 我不知道,老实说,我无法测试它。也许您应该尝试一下,然后看看它的去向?
    • 好的,它仍在编译,当我设法使用所有依赖项运行时,我可以接受这个答案
    猜你喜欢
    • 1970-01-01
    • 2012-06-14
    • 2012-10-06
    • 2013-08-11
    • 1970-01-01
    • 1970-01-01
    • 2011-10-13
    • 2015-09-26
    • 1970-01-01
    相关资源
    最近更新 更多