How to find all the classes of a package in Java

+1 vote
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
• 330 points

edited Nov 16, 2020 by Juan 347,805 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
• 330 points

selected Nov 17, 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;

Hope it helps!

To know more about Java, It's recommended to join our Java Training in Chennai today.

answered Nov 16, 2020 by Niroj
• 82,880 points

edited Oct 7, 2021 by Sarfaraz
But does it work on Java 9 and later?

Yes,it should work!!

webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP