java - 如何从另一个 JRT 读取类(class)?

标签 java jvm

从 Java 11 开始,如何读取另一个运行时镜像的内容?

为了列出 Java 运行时镜像的内容,JEP 220建议以下解决方案:

A built-in NIO FileSystem provider for the jrt URL scheme ensures that development tools can enumerate and read the class and resource files in a run-time image by loading the FileSystem named by the URL jrt:/, 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/

相关文章:

java - 如何减去 x 个工作日

java - 如何限制 CriteriaBuilder 查询中的记录数?

java - 将最大和最小 JVM 堆大小设置为相同是否很好?

java - Jboss GC不释放内存

java - 了解元空间大小

java - 读取文件并将行作为字节进行操作的最优雅的方法

Java 如何创建 UTC 并向同一个 UTC 对象添加几毫秒

docker - 更改 Solr 的 JVM 参数

java - 使用 jsch 执行多个 shell 脚本

java - Spring Boot应用程序不使用jemalloc