【发布时间】:2020-12-28 20:52:28
【问题描述】:
我尝试使用Refections 获取一组实现 接口IDispatchIdsReplaceable 的类。现在我要做的是遍历这些类,在循环中调用接口方法(重写方法)并执行实现。我该怎么做?
伪代码:
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
}
}
在其他一些方法中,需要这个函数
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
}
当我在循环中运行 classImplementingInterface.replace() 时,它给了我错误
Cannot resolve method 'replace' in 'Class'
【问题讨论】:
标签: java loops generics reflection interface