11339/retrieve-all-the-implementations-of-an-interface-in-java
Can someone explain how to retrieve the entire list of the implementations of an interface in Java?
Hi...I think you can achieve this by using the following:
Reflections reflections = new Reflections("firstdeveloper.examples.reflections"); Set<Class<? extends Fruit>> classes = reflections.getSubTypesOf(Fruit.class);
ServiceLoader<Fruit> loader = ServiceLoader.load(Fruit.class); for (Fruit implClass : loader) { System.out.println(implClass.getClass().getSimpleName()); // prints Apple, Mango }
package-level annotation
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()); } } }
and the annotation definition:
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PACKAGE) public @interface MyPackageAnnotation { Class<?>[] implementationsOfPet() default {}; }
and you need to declare the package-level annotation in a file named package-info.java inside that package. here are sample contents:
@MyPackageAnnotation(implementationsOfPet = {Apple.class, Mango.class}) package examples.reflections;
Note that only packages that are known to the ClassLoader at that time will be loaded by a call to Package.getPackages(). In case you need to know more about Java interface, join our Java training class today.
Take a look to this example: https://github.com/burningwave/core/wiki/How-retrieve-all-classes-that-implement-one-or-more-interfaces
You can also have a look here: To ...READ MORE
You could use recursion to do this. Try ...READ MORE
There are different ways you could do this ...READ MORE
I happened to find a java class "jdk.nashorn.internal.ir.debug.ObjectSizeCalculator", ...READ MORE
I am currently an AP Computer Science ...READ MORE
Extends : This is used to get attributes ...READ MORE
You've got two problems: 1) You're using Collections.sort (which takes ...READ MORE
Well let me draw a clear line ...READ MORE
Of the three, LinkedList is generally going to give ...READ MORE
Try with BurningWave core library. Here an ...READ MORE
OR
At least 1 upper-case and 1 lower-case letter
Minimum 8 characters and Maximum 50 characters
Already have an account? Sign in.