如何在没有反射和动态代理的情况下简单地显式调用默认方法?
How to explicitly invoke default method simply, without reflection and dynamic Proxy?
我在 Java 8 中阅读了有关默认方法的内容,但我被困在一件事上 - 有没有一种方法可以从接口调用默认方法而不实现它,或者使用动态代理?通过使用简单的方法,如以下方法:
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 was connected only with invocation in implementing method, and two others was connected with dynamic Proxy using reflection and reflection。
这些解决方案非常复杂,我想知道是否有更简单的方法。我也阅读了这些文章,但没有找到解决问题的方法。如有任何帮助,我将不胜感激。
如果接口只有一个方法,或者它的所有方法都有默认实现,您需要做的就是创建一个匿名实现,该实现不会实现您希望的方法打电话:
(new DefaultTestInterface() {}).method1();
我在 Java 8 中阅读了有关默认方法的内容,但我被困在一件事上 - 有没有一种方法可以从接口调用默认方法而不实现它,或者使用动态代理?通过使用简单的方法,如以下方法:
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 was connected only with invocation in implementing method, and two others was connected with dynamic Proxy using reflection and reflection。
这些解决方案非常复杂,我想知道是否有更简单的方法。我也阅读了这些文章,但没有找到解决问题的方法。如有任何帮助,我将不胜感激。
如果接口只有一个方法,或者它的所有方法都有默认实现,您需要做的就是创建一个匿名实现,该实现不会实现您希望的方法打电话:
(new DefaultTestInterface() {}).method1();