How to add resources to two modular jars in same-named folders?

Viewed 158

Assuming we have two jar files with two different modules. Both jar-files include some resources (lets say png-files) in a folder called images in their jar. When I now try to start a module in java I get the following error:

Error occurred during initialization of boot layer
java.lang.LayerInstantiationException: Package images in both module A and module B

Although my images folder is not meant to be a package but is just a folder containing resources. So how can I get two modules with an images-folder onto my module-path?

1 Answers

How to add resources to two modular jars in same-named folders?

While it is possible to do this by putting the resources under a path that is not a valid package name, such as META-INFO/resources or another path with a - hyphen in it, I would advice against doing so since such resources are not encapsulated, and might not be uniquely identifiable with some APIs.

In other words: ANY code in the application can load a resource that is not inside a valid package, not just the code of the module in the jar that contains the resource.

As well as: if the resource does not have a unique name based on it's path inside the jar, only one of the resources with the same name can be found by the ClassLoader.findResource API.


My advice would be to create a package in your module that has the same name as the module, with the .images suffix. e.g. mod.foo.images, and then put your resources in that package. Then load the resource with the modular resource loading API:

MyClass.class.getModule().getResourceAsStream("mod/foo/images/my_image.jpg")

That way the resource would only be loadable by code in the same module (mod.foo, as long as you put it on the module path), as well as avoiding any ambiguity with resource names.

Related