1

Is it possible in Java to check if an interface has been implemented?

If yes:

  • Is there an official way to do this?
  • How is it possible?
  • And is it possible to check if it is implemented in an external library (jar)?

If no:

  • Is there a workaround to check this?

An example of my problem can be this:

My interface is implemented in an external library(jar), I want to start one of my threads only if this interface has an implementation. (Obviously, I want to check it at runtime without know nothing about the external library.)

I accept also suggestion on possible workaround to solve this problem.

Note: I can't add framework that help in this task.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Zig Razor
  • 3,381
  • 2
  • 15
  • 35
  • Are you using any dependency injection framework in your app? Not sure if it'll help right now but it might be a valuable info for future answerers. – lealceldeiro Dec 23 '20 at 09:31
  • 1
    Well there is no "official" way as in built-in. You'd need to scan all classes on the classpath and check whether they implement the interface. Depending on your actual requirements, i.e. what you really want to do (more details would be needed), and your environment/teck stack there could be other ways to do that. Spring or CDI would provide lookup of beans by interface, the [Java SPI](https://docs.oracle.com/javase/tutorial/ext/basics/spi.html) might help as well. – Thomas Dec 23 '20 at 09:32
  • @lealceldeiro no i don't have any dependency injection framework in my app – Zig Razor Dec 23 '20 at 09:40
  • 1
    Does this solve your problem? https://stackoverflow.com/questions/347248/how-can-i-get-a-list-of-all-the-implementations-of-an-interface-programmatically – hradecek Dec 23 '20 at 10:13
  • @Thomas i don't want to use Spring or CDI. What do you mean when say: " You'd need to scan all classes on the classpath and check whether they implement the interface"? You mean i need to scan at filesystem level? – Zig Razor Dec 23 '20 at 12:06
  • @hradecek no this not answer my question. I don't know if an implementation exists, and i can't declare an object to verify the "instanceof". – Zig Razor Dec 23 '20 at 12:08
  • Well, you'd have to get all classes on the classpath which would mean classes in libraries and indivdual class files and regardless of whether they have been loaded by a classloader yet. There are libraries like [reflections](https://github.com/ronmamo/reflections) or [classgraph](https://github.com/classgraph/classgraph) which can help with this. However there might be easier ways to achieve what you want if you'd elaborate on that. – Thomas Dec 23 '20 at 13:16

0 Answers0