ClassLoader API to look up class files

Rafael Winterhalter rafael.wth at gmail.com
Sat Sep 21 21:14:40 UTC 2024


Hello,
It is a quite common need for Java agents to resolve class files for Java
classes by their name. Normally, this is done by requesting a resource from
the class loader. So if a class:

pkg.SampleClass

is requested, the agent calls
ClassLoader.getResourceAsStream("pkg/SampleClass.class"). This normally
works well, with a few exceptions where class loaders do not implement
lookup.

However, with multi-release jars this is less reliable. In theory, on a
Java 23 VM I would need to request all from:

"META-INF/versions/23/pkg/SampleClass.class"
to
"META-INF/versions/9/pkg/SampleClass.class"
and finally
"pkg/SampleClass.class"

This is of course not scalable. To ease the process, I wanted to suggest to
add a method to class loader:

public InputStream getClassFileAsStream(String name, short version) {
  return getResourceAsString(name.replace('.', '/') + ".class");
}

In the default implementation, this would simply fall back to finding the
resource in the standard location. However, class loaders could override
this method to look up the class file for a class from different locations.
Normally, the class loader has better knowledge of the represented class
files and can look up multi-release files more efficiently than by
iterating over a growing number of locations.

Is this something that could be considered?

Thanks! Rafael
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/core-libs-dev/attachments/20240921/64129fae/attachment.htm>


More information about the core-libs-dev mailing list