jeudi 22 août 2019

How to retrieve some resources from external JAR file using reflections

Ok, I know that similar questions have been already posted here, and in fact, my solution is feeding from them.

The idea I have is to have some modules (a module is a set of XML files in a folder inside a JAR file) that can be added to an application by the user. That means that the user can put some jars in a predefined folder, and all resources from this JARs must be available for the application. For this purpose, I need to load all JARs from an external folder, and retrieve the XMLs as resources. The JAR files, usually have not any class file, but maybe at the future can have it.

Also the application has a "default" module that is already inside its resources folder. This module is working fine and I can list all XMLs inside it using Reflections.

My code from retrieving all XML files using Reflection is very simple:

    final Set<String> resources = new Reflections(CustomPath.MODULES_FOLDER, new ResourcesScanner()).getResources(Pattern
            .compile(".*\\.xml"));

that returns a Set of strings similar to modules_folder/module_name/file1.xml.

And the code to load a Jar file is using a URLClassLoader:

Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
        method.setAccessible(true); // promote the method to public access.
        method.invoke(loader, new Object[] { url });

As far as I have understood, the resources are available from the URLClassLoader. In fact, I can do something like:

URLClassLoader.getSystemResource("modules_folder/module_name/file1.xml").

And the file is loaded and If I put an invalid path, an error is thrown. Also I need to know the 'module_name' that is not predefined. Then is not a solution.

If I run again the method to retrieve the resources using Reflection, it is only retrieving the files inside the resources folder of the project. No resource from the JAR is retrieved.

Then, I cannot understand why reflections is unable to get the files from the JAR files if are already loaded. I am not sure if Reflections is unable to access to the URLCLassLoader for any reason, or that must be used in a different way.

The question is... Why Reflections is not able to access to the resources from a JAR loaded at runtime? And if it is a limitation, what is the best approach to do it without any Java classes inside the external JAR file?





Aucun commentaire:

Enregistrer un commentaire