【发布时间】:2017-01-26 02:56:41
【问题描述】:
我正在阅读 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仅与实现方法中的调用相关,另外两个与dynamic Proxy using reflection和 reflection相关。
这些解决方案相当复杂,我想知道是否有更简单的方法。我也阅读了这些文章,但我没有找到解决问题的方法。如果有任何帮助,我将不胜感激。
【问题讨论】:
-
所以要使用没有实例的实例方法???
-
您的问题有些混乱。 java 8 接口的默认方法 已经是一个实现。如果您没有需要不同实现的特定于类的行为,则只需实现接口,省略您要用作默认值的方法。如果你想从 interface 调用方法而不是考虑使用 static 关键字来定义它。
-
不,@fabian,我正在考虑以某种方式包含实例化的解决方案。
-
已经实现了默认方法。您不必重新实现它。
标签: java methods java-8 default