how to list all the classes in a subpackage of a class in java, when executing a jar file?

41 Views Asked by At

I decided to define classes with similar functionality in sub package, list all the classes in this sub package programatically and call their method. Piece of cake, but only running in my IDE. When I deployed the stuff, the things stopped working. I forgot, that I shouldn't use java.io.File I see the similar topic here: Java Jar file: use resource errors: URI is not hierarchical

But I cannot find anything useful for me. They say to open an InputStream, but I cannot figure out how to use this inputstream to list the classes in the subpackage? Using the

<some resource>.toExternalForm());

caused the unit tests to fail. In general my code is like this:

 String packageName = MyClass.class.getPackage().getName();
 String subpackageName = packageName + ".announcements";
 URL packageUrl =   MyClass.class.getClassLoader().getResource(subpackageName.replace('.', '/'));
 File packageDirectory = new File(packageUrl.toURI());
 if (packageDirectory.exists()) {
  String[] files = packageDirectory.list();
  ...and so on...
 }
 
0

There are 0 best solutions below