Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to find all the classes of a package in Java

I need to find all the classes of certain packages: what is the best way to do this?
by

2 Answers

espadacoder11
Hello @Juan ,

You could use Reflections:

private Class<?>[] scanForTasks(String packageStr) {
Reflections reflections = new Reflections((new ConfigurationBuilder()).setScanners(new Scanner[]{new SubTypesScanner(), new TypeAnnotationsScanner()}).setUrls(ClasspathHelper.forPackage(packageStr, new ClassLoader[0])).filterInputsBy((new FilterBuilder()).includePackage(packageStr)));
Set classes = reflections.getTypesAnnotatedWith(Task.class);
Class[] taskArray = (Class[])classes.toArray(new Class[classes.size()]);
return taskArray;
}
}
sandhya6gczb
Due to the dynamic nature of class loaders, this is not possible. Class loaders are not required to tell the VM which classes it can provide, instead they are just handed requests for classes, and have to return a class or throw an exception.

However, if you write your own class loaders, or examine the classpaths and it's jars, it's possible to find this information. This will be via filesystem operations though, and not reflection. There might even be libraries that can help you do this.

If there are classes that get generated, or delivered remotely, you will not be able to discover those classes.

The normal method is instead to somewhere register the classes you need access to in a file, or reference them in a different class. Or just use convention when it comes to naming.

Login / Signup to Answer the Question.