MethodHandles.Lookup.defineResource?

Alan Bateman Alan.Bateman at oracle.com
Wed Aug 29 06:53:39 UTC 2018


On 28/08/2018 22:21, Stephen Colebourne wrote:
> :
> The key point here is that this all worked before Java 9 modules. But
> since resources are now encapsulated, adding a new ClassLoader is no
> longer sufficient to inject a resource, as it doesn't get the right
> module encapsulation that way.
The article you cited relied on two hacks and was very fragile (run the 
example with JDK 8 and -Djava.system.classloader set on the command line 
and you'll see how it breaks with older JDK releases too).

In general, and aside from special support for agents, the JDK has never 
had a supported mechanism for dynamically extending the class path. The 
right way to do this type of thing is to create your own ClassLoader 
that you specify to Class.forName to load classes or invoke its 
getResource to locate resources that you want to make available.


>   My experience more generally has been
> that encapsulating resources in Java 9 modules has broken key
> assumptions in almost every library I maintain.
Existing libraries should work on the class path as before. The only two 
cases where you may have issues with existing deployments are:

1. Code that invokes getResourceXXX on a Class in a named module on the 
assumption that the resource to be found on the class path. This one has 
come up a few times, one of the examples discussed here was in Derby DB 
where it used Object.getResource(...) to locate a derby resource file. 
That one is easily fixed to invoke getResource on one of the classes in 
the same JAR file as the resource.

2. Code uses getResourceXXX methods to locate JDK internal (non-class) 
resources. This hasn't come up very often.

This is of course documented in the JDK 9 release notes.

> Remember that library
> maintainers now have to to develop and test code like this for three
> different environments, Java 8, Java 9 classpath and Java 9 modulepath
> - its very painful.
If a library maintainer migrates a library to an explicit module (I 
really mean "explicit" here, as in writing a module-info.java) then they 
will need to take resource encapsulation into account.

-Alan.


More information about the core-libs-dev mailing list