简体   繁体   English

有没有办法在Eclipse中自动生成包装器?

[英]Is there a way to autogenerate wrappers in Eclipse?

I have to create several proxies, to add, for example, logging. 我必须创建几个代理,例如添加日志记录。 Something like that: 像这样的东西:

interface IMath {
    public int add(a, b);
}

class Math implements IMath {
    public int add(a, b) { return a + b; }
}

class MathWithLogs implements IMath {
    private IMath realMath;
    public int add(a, b) {
        Log.d("tag", "valueable info");
        return realMath.add(a, b);
    }
}

Everything is fine as long as these interfaces aren't 20 methods and I have to add something to just one. 一切都很好,只要这些接口不是20种方法,我只需要添加一些东西。

My question is, is there a way to autogenerate wrapper classes with some plugin for eclipse? 我的问题是,有没有办法用eclipse的一些插件自动生成包装类?

Or maybe there is a way to do something with annotations to invoke methods from realMath unless stated otherwise (like @Override)? 或者除非另有说明(比如@Override),否则有一种方法可以使用注释来调用realMath中的方法?

Right click in any source file (.java) and navigate to source -> Override/Implement Methods/Generate Delegate Methods. 右键单击任何源文件(.java)并导航到source -> Override/Implement Methods/Generate Delegate Methods.

The first will paste the body of all methods of your immediate interface. 第一个将粘贴您的直接接口的所有方法的主体。 the second will do the same for all the hierarchy up to Object(I guess, not sure). 第二个将对所有层次结构执行相同的操作(我猜,不确定)。 Hope this helps. 希望这可以帮助。

是的,有一个名为“生成委托方法”的源生成器,它将完全按照您的要求执行。

It took me a while after reading the other answers to work out exactly what to do. 在阅读了其他答案后,我花了一段时间才弄明白该做什么。 The solution is: 解决方案是:

  1. Create your (initially empty) wrapper class which implements the required interface. 创建实现所需接口的(最初为空)包装类。 Make sure to uncheck "Inherited abstract methods" when creating the class. 确保在创建类时取消选中“继承的抽象方法”。
  2. Inside your new wrapper class (which will show an error at the moment due to the fact that it lacks the interface implementations), create a field which has type equal to the required interface. 在新的包装器类中(由于它缺少接口实现,此时将显示错误),创建一个类型等于所需接口的字段。
  3. Right click the field you just created and select Source -> Generate Delegate Methods. 右键单击刚刚创建的字段,然后选择Source - > Generate Delegate Methods。
  4. Check the methods you want to create and click OK. 检查要创建的方法,然后单击“确定”。
  5. Finally, add a single-arg constructor or a setter method for the field (it's not automatically generated as part of this process). 最后,为字段添加单arg构造函数或setter方法(它不会作为此过程的一部分自动生成)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM