如何解决如何遍历实现通过Java Refections获取的类和类的调用接口方法的接口?
我尝试使用IDispatchIdsReplaceable
来获取实现接口Refections
的一组类。现在,我要做的是遍历这些类,在循环内调用接口方法(重写的方法)并执行实现。我该怎么办?
伪代码:
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'
解决方法
这里缺少的是应该从实例中调用replace
方法,因此您需要首先创建该类的实例,然后调用replace
:
for (Class<? extends IDispatchIdsReplaceable> classImplementingInterface : classesImplementingIDispatchIdsReplaceable) {
IDispatchIdsReplaceable instance = classImplementingInterface.getConstructor().newInstance(); // Choose the right constructor,here I'm using the default one
instance.replace();
}
编辑:
默认构造函数应在子类中显式实现,否则您将获得NoSuchMethodException
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。