Programmatically Retrieving Class Implementations of an Interface in Java
Java reflection offers flexible mechanisms for introspecting classes and interfaces. In this context, developers can leverage reflection to retrieve a list of all classes that implement a specific interface.
Reflection-Based Approach
Using the reflections library, developers can effortlessly retrieve subclasses of an interface as follows:
Reflections reflections = new Reflections("firstdeveloper.examples.reflections"); Set<Class<? extends Pet>> classes = reflections.getSubTypesOf(Pet.class);
ServiceLoader Approach
The Java ServiceLoader provides an alternative approach for discovering interface implementations. This technique requires defining the interface as a Service Provider Interface (SPI) and declaring its implementations:
ServiceLoader<Pet> loader = ServiceLoader.load(Pet.class); for (Pet implClass : loader) { System.out.println(implClass.getClass().getSimpleName()); // prints Dog, Cat }
Package-Level Annotation Approach
With package-level annotations, we can declare the implementations of an interface within the package-info.java file:
@MyPackageAnnotation(implementationsOfPet = {Dog.class, Cat.class}) package examples.reflections;
Then, we can retrieve these implementations using reflection:
Package[] packages = Package.getPackages(); for (Package p : packages) { MyPackageAnnotation annotation = p.getAnnotation(MyPackageAnnotation.class); if (annotation != null) { Class<?>[] implementations = annotation.implementationsOfPet(); for (Class<?> impl : implementations) { System.out.println(impl.getSimpleName()); } } }
The above is the detailed content of How Can I Programmatically Find All Classes Implementing a Given Interface in Java?. For more information, please follow other related articles on the PHP Chinese website!