用 Java 实现多个接口 - 有没有办法委托? [英] Implementing multiple interfaces with Java - is there a way to delegate?

查看:24
本文介绍了用 Java 实现多个接口 - 有没有办法委托?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个基类来实现多个接口和许多方法,示例如下.

I need to create a base class that implements several interfaces with lots of methods, example below.

有没有更简单的方法来委托这些方法调用,而不必创建大量重复的方法?

Is there an easier way to delegate these method calls without having to create a horde of duplicate methods?

public class MultipleInterfaces implements InterFaceOne, InterFaceTwo {

    private InterFaceOne if1;
    private InterFaceTwo if2;

    public MultipleInterfaces() {
      if1 = new ImplementingClassOne();
      if2 = new ImplementingClassTwo();
    }

    @Override
    public void classOneMethodOne { if1.methodOne(); }
    @Override
    public void classOneMethodTwo { if1.methodTwo(); }
    /** Etc. */


    @Override
    public void classTwoMethodOne { if2.methodOne(); }
    @Override
    public void classTwoMethodTwo { if2.methodTwo(); }
    /** Etc. */

}

推荐答案

如上所述,没有办法.但是,有点像样的 IDE 可以自动生成委托方法.比如Eclipse就可以做到.首先设置一个模板:

As said, there's no way. However, a bit decent IDE can autogenerate delegate methods. For example Eclipse can do. First setup a template:

public class MultipleInterfaces implements InterFaceOne, InterFaceTwo {
    private InterFaceOne if1;
    private InterFaceTwo if2;
}

然后右键单击,选择 Source > Generate Delegate Methods 并勾选 if1if2 字段,然后单击 OK.

then rightclick, choose Source > Generate Delegate Methods and tick the both if1 and if2 fields and click OK.

另见以下屏幕:

这篇关于用 Java 实现多个接口 - 有没有办法委托?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆