Devops

How to find all the classes of a package in Java

GU Asked by Gulsham · 11-08-2023
▲ 0 upvotes 509 views 0 comments
The question
I am seeking guidance on how to identify all the classes within specific packages for my project. What would be the most effective method to accomplish this?

2 answers

▲ 0
JU
Answered on 12-10-2023
While browsing the internet, I came across a web page that provides an example compatible with Java versions 8 through 16. What are your thoughts on this?
▲ 0
LO
Answered on 11-11-2023

Hello

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!

Share your thoughts

Your email address will not be published. Required fields are marked (*)

Still have questions? Schedule a free counselling session

Our experts are ready to help you with any questions about courses, admissions, or career paths. Get personalized guidance from industry professionals.

Book Free Session

Book Free Session