Home >Java >javaTutorial >How Can I Programmatically Get a List of Java Interface Implementations?

How Can I Programmatically Get a List of Java Interface Implementations?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-09 07:48:07917browse

How Can I Programmatically Get a List of Java Interface Implementations?

Getting a List of Interface Implementations in Java Programmatically

Exploring various ways to obtain a list of all the implementations of an interface in Java, this article delves into the realms of reflection and other techniques.

Reflection with Reflections Library

If incorporating an additional dependency is not a concern, the reflections library offers a convenient solution. It allows you to retrieve the desired information with concise code:

Reflections reflections = new Reflections("firstdeveloper.examples.reflections");
Set<Class<? extends Pet>> classes = reflections.getSubTypesOf(Pet.class);

ServiceLoader and SPI

ServiceLoader, as mentioned earlier, utilizes the Service Provider Interface (SPI) model. This approach requires you to declare Pet as an SPI and specify its implementations in a specific resources/META-INF/services/ file. The code for this method is as follows:

ServiceLoader<Pet> loader = ServiceLoader.load(Pet.class);
for (Pet implClass : loader) {
    System.out.println(implClass.getClass().getSimpleName()); // prints Dog, Cat
}

Package-Level Annotation

The package-level annotation approach defines an annotation in a package-info.java file within a specific package, specifying the implementations of an interface. The usage of this technique is demonstrated below:

Package Annotation:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PACKAGE)
public @interface MyPackageAnnotation {
    Class<?>[] implementationsOfPet() default {};
}

Package-info.java:

@MyPackageAnnotation(implementationsOfPet = {Dog.class, Cat.class})
package examples.reflections;

Code:

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 Get a List of Java Interface Implementations?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn