Java: How to get all implementations of an Interface

in #java2 years ago

You've implemented them all. That was the hard part. Listing them should be easy!

How to list all known implementations of an interface is something that I'm asked a lot. I'm biased towards two ways of doing it.

samuel-horn-af-rantzien-8PKEeac1hzw-unsplash.jpg
By the very talented Samuel Horn af Rantzien

Java 6 brought us the Service Provider Interface (SPI) which has at its core the ServiceLoader class, responsible for loading implementations.

Java itself uses the Service Provider Interface (SPI) in many ways:

  • CurrencyNameProvider
  • NumberFormatProvider
  • TimeZoneNameProvider

Using it is straightforward. You just have to declare all providers in a provider configuration file. In order to do so, put them in a META-INF/services/com.example.providers.CustomProvider and the content of this file will list the existing providers:

Read the rest of the article here:
https://wasteofserver.com/java-how-to-get-all-implementations-of-an-interface/