How to find all the classes of a package in Java

+2 votes
In my project I need to find all the classes of certain packages: what is the best way to do this?
Nov 14, 2020 in Java by Juan
• 340 points

edited Nov 16, 2020 by Juan 293,180 views

2 answers to this question.

+3 votes
Best answer

Looking on internet I found this page with an example and it works on Java version ranging from 8 to 16: what do you think about?

answered Nov 16, 2020 by Juan
• 340 points

selected Nov 16, 2020 by Juan
0 votes

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;
    }
}
answered Nov 16, 2020 by Niroj
• 82,720 points
But does it work on Java 9 and later?

Yes,it should work!!