14

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?

newbie
  • 24,286
  • 80
  • 201
  • 301
  • If you mean, you want to find all implementations once as a development exercise, I'd go with the tool Bozho pointed you at. If you mean at runtime, as part of your program, like Stephen C I'd strongly recommend you do something else. :-) – T.J. Crowder Jun 26 '10 at 07:52
  • possible duplicate of [Find java classes implementing an interface](http://stackoverflow.com/questions/435890/find-java-classes-implementing-an-interface) – Joachim Sauer Jun 26 '10 at 07:59

2 Answers2

26

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

Bren
  • 2,148
  • 1
  • 27
  • 45
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 1
    +1 I never knew `java.util.ServiceLoader` existed - very handy. – Duncan Jones Apr 29 '14 at 08:15
  • Thanks for the answer! Whilst you don't recommend it I have a usecase that seems a good fit for this solution and I can run the query asynchronously without greatly affecting the running of the application. Then I provide the results only when they have finished being gathered. – Steve McDowell May 20 '15 at 08:31
8

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216