如何在Java 9中获取classpath中的jar文件和文件夹列表?

时间:2018-08-10 21:50:32

标签: java classpath java-9 java-compiler-api

我知道您不能更改 Java 9中的类路径,因为我读到以下内容:Add jar to classpath at runtime under java 9

我只想列出当前在Classpath上的jar文件和文件夹,以便为Java编译器构建命令行参数。

// Construct compile command options
// According to: http://java.sun.com/j2se/1.5.0/docs/tooldocs/solaris/javac.html
// The directory specified by -d is not automatically added to your
// classpath, so we'll add it manually.
String[] args = new String[] {"-d", classDir,
                              "-classpath", classPath,
                              "-encoding", "UTF-8",
                              srcFile};

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int ret = compiler.run(null, out, err, args);

要在Java 8中构造类路径,我将其转换为URLClassLoader,这在Java 9中是非法的:

ClassLoader myCl = SimpleJavaCompilerTest.class.getClassLoader();
URLClassLoader myUcl = (URLClassLoader) myCl;
for (URL url : myUcl.getURLs()) {
    System.out.println(url.toString().replace("file:", ""));
}

产生的(GOOD)输出如下:

/tools/idea-IU-181.4445.78/lib/idea_rt.jar
...
/tools/idea-IU-181.4445.78/plugins/junit/lib/junit5-rt.jar
/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/charsets.jar
...
/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/rt.jar
/blah/myApp/target/test-classes/
/blah/myApp/target/classes/
/home/me/.m2/repository/commons-fileupload/commons-fileupload/1.3.3/commons-fileupload-1.3.3.jar
...
/home/me/.m2/repository/org/slf4j/slf4j-api/1.7.25/slf4j-api-1.7.25.jar

我尝试了:Scanning classpath/modulepath in runtime in Java 9,但是它产生了约19,000个类文件的列表,这些文件是openjdk的一部分,但不是我项目中的jar文件或类文件夹。像(不良):

java/awt/desktop/ScreenSleepListener.class
...
javax/accessibility/AccessibilityProvider.class
...
jdk/dynalink/beans/AbstractJavaLinker$1.class
...
META-INF/providers/org.graalvm.compiler.code.HexCodeFileDisassemblerProvider
...
module-info.class
...
netscape/javascript/JSException.class
...
org/graalvm/compiler/api/directives/GraalDirectives.class
...
org/ietf/jgss/ChannelBinding.class
...
org/jcp/xml/dsig/internal/SignerOutputStream.class
...
org/w3c/dom/xpath/XPathResult.class
...
org/xml/sax/AttributeList.class
...
sun/applet/AppContextCreator.class
...
sun/util/spi/CalendarProvider.class
...

我需要特定于我的项目的jar文件和类文件夹(它们不在上面的java-9列表中)。如何在Java 9中获得它?

0 个答案:

没有答案