【问题标题】:How to explicitly invoke default method simply, without reflection and dynamic Proxy?如何在没有反射和动态代理的情况下简单地显式调用默认方法?
【发布时间】: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


【解决方案1】:

如果接口只有一个方法,或者它的所有方法都有默认实现,那么您需要做的就是创建一个实现您希望调用的方法的匿名实现: p>

(new DefaultTestInterface() {}).method1();

Demo.

【讨论】:

  • 谢谢,这正是我正在寻找的解决方案。
  • @Michał Szewczyk:您的问题明确表示“没有实现它”,而这个答案正在实现它。这根本没有任何意义。归结为您实际上问过“我如何实现接口?”......
  • @Holger 从技术上讲,您是绝对正确的:这 接口的实现。然而,这种退化的实现看起来并不像一个实现——事实上,我敢肯定,包括我自己在内的许多程序员都不会在粗略的阅读中发现这个实现。
  • 确实如此,但我并没有将其称为优势。
猜你喜欢
  • 2016-10-15
  • 2014-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-05
  • 2013-07-23
  • 2014-08-21
  • 1970-01-01
相关资源
最近更新 更多