Given the following example code
package com.test;
import org.reflections.Reflections;
import java.util.Set;
public class Main {
public interface TestA {}
public interface TestB {}
public static class Aclass implements TestA {}
public static class Bclass implements TestA, TestB {}
public static <T> Set<Class<? extends T>> getClassesThatImplement(Class<T> interfaceClass) {
Reflections reflect = new Reflections("com.test");
return reflect.getSubTypesOf(interfaceClass);
}
public static void main(String[] args) {
Set<Class<? extends TestA>> aClasses = getClassesThatImplement( TestA.class );
// Prints [class com.test.Main$Aclass, class com.test.Main$Bclass]
System.out.println(aClasses);
Set<Class<? extends TestB>> bClasses = getClassesThatImplement( TestB.class );
// Prints [class com.test.Main$Bclass]
System.out.println(bClasses);
}
}
how can I limit my method, getClassesThatImplement
to only accept interfaces so that I get compile time errors instead of runtime errors if I use a regular class? There is no common, or "root", interface I can use to "bound" my generic type <T implements ...>
. Is there even a way to do that in Java or will I have to rely on runtime checks?
Aucun commentaire:
Enregistrer un commentaire