I'm currently using reflection to get all loaded classes from the classes
field in ClassLoader
and then checking if getPackage
is equal to the package I'm searching for. One problem I'm having with this is that the classes aren't getting loaded by the ClassLoader
but I have no way to load them myself using Class.forName
because I won't know the name of the classes since they are dynamically loaded and always changing. One thing the classes all have in common is that they extend Module
. How would I go about loading all the classes from a package?
Thanks in advance.
Using the reflections API it works for sure. If it doesn't you might set it up the wrong way. I just made up this example and it prints all of the classes in the package independently from any classloader.
package com.test;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Set;
import org.reflections.Reflections;
import org.reflections.scanners.FieldAnnotationsScanner;
import org.reflections.scanners.MemberUsageScanner;
import org.reflections.scanners.MethodAnnotationsScanner;
import org.reflections.scanners.MethodParameterNamesScanner;
import org.reflections.scanners.MethodParameterScanner;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.scanners.TypeAnnotationsScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import org.reflections.util.FilterBuilder;
public class Runner {
public static void main(String[] args) {
Reflections reflections = new Reflections();
FilterBuilder TestModelFilter = new FilterBuilder().include("com.test.*");
reflections = new Reflections(new ConfigurationBuilder()
.setUrls(Arrays.asList(ClasspathHelper.forClass(Runner.class))).filterInputsBy(TestModelFilter)
.setScanners(new SubTypesScanner(false), new TypeAnnotationsScanner(), new FieldAnnotationsScanner(),
new MethodAnnotationsScanner(), new MethodParameterScanner(), new MethodParameterNamesScanner(),
new MemberUsageScanner()));
Set<Class<? extends Object>> allClasses = reflections.getSubTypesOf(Object.class);
System.out.println(allClasses);
for (Iterator it = allClasses.iterator(); it.hasNext();) {
Class<? extends Object> clazz = (Class<? extends Object>) it.next();
System.out.println(clazz.getCanonicalName());
}
}
}
I added all the imports by intention, so you can see what API it uses. Does this work for you?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With