lundi 13 février 2023

How to iterate over all classes when code is executing inside an Uber JAR?

I need to find all classes that implement an interface at runtime. I was using this code to iterate over all classes:

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
System.out.println("loading resources");
Enumeration<URL> resources = classLoader.getResources("");
Set<Class<?>> classes = new HashSet<>();
int count = 0;
while (resources.hasMoreElements()) {
count++;
...
}
System.out.printf("found %d resources\n", count);

and it worked when my application was not packaged as an Uber JAR. But when I package my application as an Uber JAR and try to run it like:

java -jar target/app.jar

There are no resources returned.

loading resources
found 0 resources

How can I fix this?

My overall problem is this: Given this pattern of execution:

java -jar app.jar

Give me all classes that implement interface X.Y.Z.





Aucun commentaire:

Enregistrer un commentaire