我知道你不能在 Java 9 中更改类路径,因为我读过以下内容:在 java 9 下运行时将 jar 添加到类路径
我只想列出当前在类路径上的 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:", ""));
}
这产生了(良好(输出,如下所示:
/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
我试过:在 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中做到这一点?
下面的代码片段将有助于获得所需的输出。
String classpath = System.getProperty("java.class.path");
String[] classPathValues = classpath.split(File.pathSeparator);
for (String classPath: classPathValues) {
System.out.println(classPath);
}
在 Java 9+ 中,您可以通过反射获得一些帮助来获取类路径 URL:
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
Field ucpField = BuiltinClassLoader.class.getDeclaredField("ucp");
ucpField.setAccessible(true);
URLClassPath classpath = (URLClassPath) ucpField.get(classLoader);
for (URL url : classpath.getURLs()) {
System.out.println(url.getFile());
}
不要忘记添加:
requires java.base
到module-info.java
文件--add-exports java.base/jdk.internal.loader=your_module_name
编译器选项--add-exports java.base/jdk.internal.loader=your_module_name
和--add-opens java.base/jdk.internal.loader=your_module_name
VM 选项