我在阅读有关 Java 8 中的默认方法的文章时陷入了困境 - 有没有一种方法可以从接口(interface)调用默认方法而不实现它,或者使用动态代理?通过使用简单的方法,例如以下方法:
interface DefaultTestInterface{
default void method1(){
//default method
}
}
class ImplementingClass implements DefaultTestInterface{
public void method1(){
//default method invocation in implementing method
DefaultTestInterface.super.method1();
}
void method2(){
//default method invocation in implementing class
DefaultTestInterface.super.method1();
}
}
public class Main {
public static void main(String[] args) {
//is there any way to simply invoke default method without using proxy and reflection?
}
}
我读过类似的问题,但是 first仅与实现方法中的调用相关联,另外两个与dynamic Proxy using reflection相关联和 reflection .
这些解决方案非常复杂,我想知道是否有更简单的方法。我也阅读了这些文章,但没有找到解决问题的方法。如果有任何帮助,我将不胜感激。
最佳答案
如果接口(interface)只有一个方法,或者它的所有方法都有默认实现,您需要做的就是创建一个匿名实现,它不实现您希望调用的方法:
(new DefaultTestInterface() {}).method1();
关于java - 如何在没有反射和动态代理的情况下简单地显式调用默认方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39555881/