从 Java 11 开始,如何读取另一个运行时镜像的内容?
为了列出 Java 运行时镜像的内容,JEP 220建议以下解决方案:
A built-in NIO
FileSystem
provider for thejrt
URL scheme ensures that development tools can enumerate and read the class and resource files in a run-time image by loading theFileSystem
named by the URLjrt:/
, as follows:FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/")); byte[] jlo = Files.readAllBytes(fs.getPath("modules", "java.base", "java/lang/Object.class"));
此代码段有效,可让我在执行代码的 Java 安装的运行时镜像中读取 java/lang/Object.class
的内容。
鉴于它的 java home,我如何让它在另一个 Java 安装中读取 java/lang/Object.class
的内容?
我已阅读 this SO answer它解释了如何从 Java 8 运行时读取 Java 运行时镜像的内容。不幸的是,这不适用于较新的 Java 运行时,因为我相信 jrt:/
的文件系统将始终指向当前的运行时镜像。
最佳答案
您仍然可以使用 this answer 中所述的 jrt:/
方案,您只需要在创建 FileSystem
对象时在环境参数中提供替代的 java.home
路径:
public static void listModules(String javaHome) throws IOException {
FileSystem fs = FileSystems.newFileSystem(
URI.create("jrt:/"),
Collections.singletonMap("java.home", javaHome));
try (Stream<Path> stream = Files.list(fs.getPath("/modules"))) {
stream.forEach(System.out::println);
}
}
或者,读取单个资源:
public static byte[] readResource(String javaHome, String module, String path) throws IOException {
FileSystem fs = FileSystems.newFileSystem(
URI.create("jrt:/"),
Collections.singletonMap("java.home", javaHome));
return Files.readAllBytes(fs.getPath("modules", module, path));
}
关于java - 如何从另一个 JRT 读取类(class)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68021188/