[英]How to create generic Java interface typed with another generic Java interface?
[英]java create a wrapper interface for another interface
我面临的问题如下 -
我正在使用第 3 方库,比如 Editor,它有一个接口EditorActions和方法 -
创建(),编辑(),删除()。
我不想在我的实现中公开EditorActions的方法。 所以我的界面会有这样的方法 -
myCreate()、myEdit()、myDelete()依次调用 EditorActions 方法。
EditorActions 只是一个接口,实现是库内部的。
如何在不实现其中任何一个的情况下链接 2 个接口?
感谢你的帮助
您可以通过在抽象 class 中公开您希望人们使用的方法来做到这一点。 然后强迫人们实施您希望他们实施的特定方法。
然后,您可以使用EditorActions
接口中的方法以及您强制实现实现的方法。
public abstract class AbstractEditorActions {
private EditorActions ea;
public AbstractEditorActions(EditorActions ea) {
this.ea = ea;
}
// In this method, you can use the methods
// from the interface and from this abstract class.
// Make the method final so people don't break
// the implementation.
public final void yourExposedMethod() {
// code
this.toImplement();
ea.doMethod();
}
protected abstract toImplement();
}
假设您从库中获取EditorActions
的实例,您可以这样做:
public class FooActions implements MyEditorActions, EditorActions{
private EditorActions internal;
public FooActions(EditorActions internal){
this.internal = internal;
}
@Override
public void create(){
internal.create();
}
@Override
public void myCreate(){
// do stuff
this.create();
}
}
这样做是用实现与您的接口相同的接口的 object 包装库 object 的实例。 然后,您只需将 object 公开为您想要的任何接口。
EditorActions a1 = new FooActions(); // a1 only shows library methods
MyEditorActions a2 = a1; // now a2 only shows your methods
如何在不实现其中任何一个的情况下链接 2 个接口?
你不能。 您正在尝试在这里进行自动魔术。 不要变魔术。 无论如何,您都必须实现其中任何一个。
或者,您必须实现自己的反射管道(或某种 AOP)来动态创建类。 后者不是微不足道的方式,通常是过度杀伤和过度工程的危险信号,只是为了避免实施相当于一个普通的委托。
OTH,如果您只想“公开”第三方接口A提供的方法的子集(例如,只有 getter 方法),您几乎可以轻松创建(通过好的旧肘油或反射库)只公开您想要的方法子集的接口B。
接口 DirtyThirdPartyInterface { StupidCrap getSomeStupidCrap(); 无效 setStupidCrap(); }
接口 MySanitizedInterface { StupidCrap getSomeStupidCrap(); // setter 不是这个接口的一部分 }
然后使用 Spring AOP 或类似的东西或几个反射库之一,然后您可以自动生成 MySanitizedInterface 的实现作为 AOP 拦截器,它只是代理对 getter 的调用(通过反射)到 getter第 3 方接口。
但是再一次,为了简单地避免相当于简单的手工编码,这是很多废话(更不用说第 3 方库依赖项了)。 很难找到一个真实世界的案例来证明所有管道问题的合理性。 如果我遇到这样的事情,我首先想到的是“红旗”。 当然是 YMMV。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.