I would like to list all the files of a given package inside a module in java 9.
I'm using this code to accomplish the task (I've also tried with different ways to get the class loader):
String packageName= io.packageToBeScanned.AnyClass.class.getPackageName();
String packageNameToUri= packageToUri(packageName);
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
//ClassLoader classLoader = ClassLoader.getPlatformClassLoader();
//ClassLoader classLoader = ClassLoader.getSystemClassLoader();
//ClassLoader classLoader = getClass().getClassLoader();
//ClassLoader classLoader = getClass().getModule().getClassLoader();
Enumeration<URL> resources = classLoader.getResources(packageNameToUri);
while(resources.hasMoreElements()){
URL resource = resources.nextElement();
File f = new File(resource.getFile());
...
}
All fine all good, but when I add the module-info file, nothing works.
When I run a junit test (in src/test/jata) it correctly scans the package under src/main/java/io/packageToBeScanned only if the module-info is not present.
I've tried to open the module, but without success. I've also tried to open the package: no success. Or to open the package to moduleName
: no success.
module moduleName {
exports io.packageToBeScanned;
}
I know that modules were thought as a way to hide packages from the outside, but it's the library itself that I want to scan itself! I'm out of ideas...
Thank you.
-- UPDATE --
I saw that if I run a junit,
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.6.2</version>
</dependency>
then the error occurs. If instead I run the code in a public static void main(String[] args)
then no error occurs...
Printing resource.getFile()
without module-info results in
/target/test-classes/io/packageToBeScanned
/target/classes/io/packageToBeScanned
With module-info, instead,
/target/test-classes/io/packageToBeScanned/
/target/test-classes/io/packageToBeScanned
It doesn't care if the scanned package contains private, package-private, or public classes.