【问题标题】:How do I loop through the interface implementing Classes (and call interface methods of the class) that I have fetched through Refections in Java?如何遍历通过 Java 中的 Refects 获取的实现类的接口(并调用类的接口方法)?
【发布时间】: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


    【解决方案1】:

    这里缺少的是应该从一个实例调用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

    【讨论】:

    • 不同的类不会有不同的构造函数吗?另外,我尝试了您建议的方式。它在 .getConstructor() Unhandled exception: java.lang.NoSuchMethodException @Ismail 处显示和错误
    • 你的类中是否存在默认构造函数?
    • 是的,我明白,但它显示错误。不知道为什么?
    • 您可以使用 try 和 catch 块来处理和自定义异常消息或在方法的标头中抛出这些异常,但我认为最好使用 try 和 catch 块。
    • 您是否还有其他问题或此解决方案效果很好?如果您认为这回答了您的问题,请不要忘记将其作为正确答案进行检查。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-24
    • 2014-03-13
    • 2017-08-21
    • 2020-09-27
    • 1970-01-01
    • 2012-07-24
    • 1970-01-01
    相关资源
    最近更新 更多