ClassLoader.getResources vs Module.getResourceAsStream

Alan Bateman Alan.Bateman at oracle.com
Sat Jul 14 15:31:14 UTC 2018


On 14/07/2018 14:00, Michał Zegan wrote:
> Hello.
> When reading docs for jdk9 and jdk10 it seems that those methods work in
> a bit different way when it goes to encapsulation:
> Module.getResourceAsStream will retrieve the resource without a problem
> if a package is opened to the caller module, probably including the fact
> that it will find a resource when the calling module is the same as one
> represented by the module object.
> But, ClassLoader.getResources and other resource methods seem to require
> unconditional package open.
> Why? I don't quite understand that distinction.
ClassLoaders, especially in a delegation chain, have no notion of "who" 
is trying to locate the resource. The ClassLoader.getResourceXXX methods 
are also not final. All told, the ClassLoader.getResourceXXX cannot 
reliably support qualified opens so this is why they are specified to 
only locate resources in modules when the package is open to all modules.

The general guideline is to use Class or Module getResourceXXX when you 
want to locate a resource in your own module or another specific module. 
Use ClassLoader.getResourceXXX when you want to search the class path. 
If you follow that then it makes it a lot easier to migrate existing 
code to modules.

-Alan


More information about the jigsaw-dev mailing list