I want to list/enumerate (at runtime) in my Java program all classes that implements a given interface, and retrieve the class name. Is it possible ? How can i do ?
Asked
Active
Viewed 997 times
0
-
possible duplicate of [How do you find all subclasses of a given class in Java?](http://stackoverflow.com/questions/492184/how-do-you-find-all-subclasses-of-a-given-class-in-java) – rsp Jan 04 '12 at 16:18
-
Pick one of http://stackoverflow.com/questions/435890/find-java-classes-implementing-an-interface and http://stackoverflow.com/questions/3123095/how-can-i-find-all-implementations-of-interface-in-classpath You may need to fine tune the results.. – Jayan Jan 04 '12 at 16:21
-
Clear duplicate of the questions listed by @Jayan – parasietje Jan 04 '12 at 16:39
2 Answers
2
To elaborate on how to do that using reflection :
You can start off with Thread.currentThread().getContextClassLoader()
.
Using a package name as path, get at the resources : Enumeration<URL> resources = classLoader.getResources(path);
Then you would have to decode the filenames from the resources, and iterate over them (recursively as some might be directories). Filter the resources for .class
files, instantiate the classes with Class.forName()
and check the interfaces they implement.

kostja
- 60,521
- 48
- 179
- 224
1
You should use java Reflection
This link offers a tutorial that cover all the thing you can do using Reflection. You can build your code starting from there

Adel Boutros
- 10,205
- 7
- 55
- 89