Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find all implementations of interface in classpath?

I'm implementing an interface and now I'd like to get all implementations of this interface in classpath. Is this possible or should I do something else?

like image 630
newbie Avatar asked Jun 26 '10 07:06

newbie


People also ask

Can we know which interfaces are implemented by a class?

Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class. By convention, the implements clause follows the extends clause, if there is one.

How do I find all implemented classes for an interface in eclipse?

Open Java Search, enter the interface name, click "Implementors" and you will "find which classes implement a particular interface."

How do you know if a class implements an interface?

A class implements an interface if it declares the interface in its implements clause, and provides method bodies for all of the interface's methods. So one way to define an abstract data type in Java is as an interface, with its implementation as a class implementing that interface.


2 Answers

The Reflections library will let you do that (to an extent):

Set<Class<? extends SomeClassOrInterface>> subTypes = 
     reflections.getSubTypesOf(SomeClassOrInterface.class);

However I wouldn't recommend that. Imagine a typical classpath with 50 external jars, each of which being a big framework like spring, hibernate, aspectj, jsf, etc. It would take much time.

If you want to have some kind of plugin mechanism, so that others can implement your interfaces and supply jars with the implementation, then look at java.util.ServiceLoader

like image 97
Bozho Avatar answered Sep 22 '22 03:09

Bozho


At best, this will be expensive. At worst (depending on the classloaders) it may be impossible.

I strongly suggest that you look for an alternative approach to the underlying problem that you are trying to address.

like image 24
Stephen C Avatar answered Sep 21 '22 03:09

Stephen C