jeudi 10 septembre 2020

How do I loop through the interface implementing Classes (and call interface methods of the class) that I have fetched through Refections in Java?

I have tried to fetch a Set of Classes that implements an interface IDispatchIdsReplaceable using Refections. Now what I want to do is loop through these classes, call the interface method (overridden methods) within the loop and perform the implementations. How can I do this?

Pseudo Code:

public interface IDispatchIdsReplaceable {
    void replace();
}

public class Class1 implements IDispatchIdsReplaceable  {
//usual class methods

@Override
void replace() {
//implementation
}

}

public class Class2 implements IDispatchIdsReplaceable  {
//usual class methods

@Override
void replace() {
//implementation
}

}

In some other method, this function is needed

Reflections reflections = new Reflections("com.company");
Set<Class<? extends IDispatchIdsReplaceable>> classesImplementingIDispatchIdsReplaceable = reflections.getSubTypesOf(IDispatchIdsReplaceable.class);

for (Class<? extends IDispatchIdsReplaceable> classImplementingInterface : classesImplementingIDispatchIdsReplaceable) {
    //classImplementingInterface.replace(); -> basically somthing like Class1.replace() or Class2.replace() along with the loop.
    //How to do the above sort of function call and run those overriden methods of the respective class
}

It gives me error when i run classImplementingInterface.replace() in the loop

Cannot resolve method 'replace' in 'Class'





Aucun commentaire:

Enregistrer un commentaire