![](/img/trans.png)
[英]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.