dimanche 21 juillet 2019

Get the list of classes that implements interface when code is used as a library in another project

I have class A implements MyInterface, class Manager, where I have load() method, and class with main, where I create instance of manager class, and call method load:

void load() throws Exception {
    final Reflections reflections = new Reflections("com.example");
    final Set<Class<? extends MyInterface>> classes = reflections.getSubTypesOf(MyInterface.class);
    for (Class<? extends MyInterface> clazz : classes) {
        MyInterface interface = clazz.newInstance();
        /..../
    }
}

My interface and class has same package "com.example". I create JAR file with this 4 classes and atach to diferent project, where I call my main method. But someone can also implements my interface, and I have no idea, how my method load() can find this new class and create new instance (and there is no restriction for package name for new class)? Maybe someone know, how to do it? In this example I use org.reflection. Tkansk!





Aucun commentaire:

Enregistrer un commentaire