ClassLoader API to look up class files

Eirik Bjørsnøs eirbjo at gmail.com
Tue Sep 24 11:44:00 UTC 2024


On Tue, Sep 24, 2024 at 12:44 PM Rafael Winterhalter <rafael.wth at gmail.com>
wrote:

> Without getting lost in specifics:
>
It is also possible to get very lost by lacking specifics :-)

> If the build plugin now wants to create instrumented versions of class
> files for a Java 17 JVM, while the build is run on a Java 21 JVM, I can
> support this for JAR files, for folders, but I cannot fetch the adequate
> resource when the underlying resource accessor is a class loader. I do not
> think that I can work around this, or do I overlook something?
>
Thanks, this narrows down your use case considerably and also explains why
you would be interested in loading resources of versions different than the
runtime version.

Does the class loader in question return JAR-form URLs? If that's the case,
you could use JarURLConnection.getJarFile() and use getInputStream to get
the versioned resource of choice:

ClassLoader loader = new URLClassLoader(new URL[] {zip.toUri().toURL()});
URL resource = loader.getResource(baseName);
if (resource.openConnection() instanceof JarURLConnection con) {
    try (var is = con.getJarFile().getInputStream(new ZipEntry(baseName))) {
        assertArrayEquals("base".getBytes(StandardCharsets.UTF_8),
                is.readAllBytes());
    }
}

Or just parse the URL to find the path to the JAR file and open it using
ZipFile/JarFile APIs.

Is the issue reported to Byte Buffy publicly available?

Thanks,
Eirik.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/core-libs-dev/attachments/20240924/2c1b5026/attachment.htm>


More information about the core-libs-dev mailing list