[英]Subclasses of a class that implements a generic interface
我正在使用Google Web Toolkit,我在實現通用接口方面遇到了問題。 我不熟悉泛型,在這里對其他人的代碼進行升級。
這就是我想要做的事情:我希望有一個通用回調接口的實現來執行一些日志記錄,然后將該實現子類化以處理特定的回調場景。
界面是這樣的:
public interface AsyncCallback<T> {
void MethodFromAsyncCallback(T result);
}
抽象和具體的實現看起來像這樣:
class CallbackBase implements AsyncCallback<Object> {
public abstract void doStuff(Object result);
public void MethodFromAsyncCallback(Object result) {
// IMPORTANT STUFF
// here are things I would like to do for all callbacks, hence the superclass.
// Then we do the subclass specific things.
doStuff(result);
}
}
class SpecificCallback extends CallbackBase
{
public void doStuff(Object result) {
Integer i = (Integer)result;
// do stuff with i
}
}
回調需要從中觸發
public interface MyServiceAsync {
public void DoSomeThing(AsyncCallback<Integer>);
}
然后它們在一個看起來像這樣的調用中匯集在一起:
MyServiceAsync myService = (MyServiceAsync)GWT.create(MyServiceAsync.class);
myService.DoSomeThing(new SpecificCallback());
這就是我們遇到問題的地方!
當GWT.create()
實現我創建的接口時,它要求指定給AsyncCallback
的類型(匹配其他類型,在此問題范圍之外的類型),因此使DoSomething(AsyncCallback<Integer>)
成為Integer而不是一個東西。 這超出了我的控制范圍。
它抱怨DoSomething()
采用AsyncCallback<Integer>
。 我正在給它一些繼承自AsyncCallback<Object>
。 我想用泛型,繼承的概念有點破碎?
所以我的問題是:
要么我怎么能將它們混合在一起,以便DoSomething()
能夠識別出SpecificCallback
符合它的要求,
或者我如何構建CallbackBase
和SpecificCallback
之間的關系以避免重復代碼,但是SpecificCallback
直接實現了AsyncCallback<Integer>
?
謝謝。
我認為你需要做的是像這樣定義CallbackBase
:
abstract class CallbackBase<T> implements AsyncCallback<T> {
public abstract void doStuff(T result);
public void MethodFromAsyncCallback(T result) {
// general stuff (T is a subclass of Object)
doStuff(result);
}
}
那么你希望你的特定回調是這樣的:
class SpecificCallback extends CallbackBase<Integer> {
public void doStuff(Integer result) {
// no need to cast
// do stuff with result
}
}
然后,接受AsyncCallback<Integer>
的DoSomething
方法將接受SpecificCallback
。
(迂腐旁注:請用Java中的小寫字母開始所有方法)
編輯
對於它的價值,我建議改變你的設計使用組合而不是繼承。 在這種情況下,不是使用抽象類CallbackBase
並擴展它,而是使用AsyncCallback<T>
的具體實現,它可能看起來像這樣:
class GeneralCallbackWrapper<T> implements AsyncCallback<T> {
private final AsyncCallback<? super T> delegate;
public GeneralCallbackWrapper(AsyncCallback<? super T> delegate) {
this.delegate = delegate;
}
public void MethodFromAsyncCallback(T result) {
// general stuff here
delegate.MethodFromAsyncCallback(result);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.