[英]Java Generics - Best way to use generic interface and its implementation
[英]Is there a way with Java Generics to take Generic parameter that requires implementation of 2 interfaces?
說我有這個代碼 -
public interface ParentInterface1 {
public List<? extends ChildInterface1> getChildren();
public void setChildren(List<? extends ChildInterface1> children);
}
public interface ParentInterface2 {
public List<? extends ChildInterface2> getChildren();
public void setChildren(List<? extends ChildInterface2> children);
}
public interface ChildInterface1 {
public String getField();
public void setField(String field);
}
public interface ChildInterface2 {
public String getField();
public void setField(String field);
}
public class LParentImpl implements ParentInterface1, ParentInterface2 {
private List<ChildImpl> list;
public List<ChildImpl> getChildren() {
return list;
}
public void setChildren(List<... wants to accept ChildImpl, which
implements ChildInterface1 & ChildInterface2> children) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
public class ChildImpl implements ChildInterface1, ChildInterface2 {
private String field;
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
}
有沒有辦法讓ParentImpl類中的setChildren()工作,而不從接口和實現中完全刪除Generic類型?
我想做點什么 -
public void setChildren(List<? extends ChildInterface1 & ChildInterface2> children)
這種接口/實現結構對非泛型類型有效,但似乎泛型的運行時擦除的某些方面可能會使這變得不可能? 或者我錯過了一些神奇的語法?
編輯:使用列表<? 擴展ChildInterface1&ChildInterface2>產生此編譯錯誤 -
...\ParentImpl.java:20: > expected
public void setChildren(List<? extends ChildInterface1 & ChildInterface2> children) {
您可以指定一個方法來獲取實現這兩個接口的對象,如下所示:
public <T extends IFirst & ISecond> void doSomething(T obj) {}
但是,在您的示例中,這並不重要,因為您的子接口都指定了相同的方法。
你可以這樣做:
public class MyClass<T extends ChildInterface1 & ChildInterface2> { ... }
你的問題沒有意義。
ParentInterface1.setChildren
接受List<ChildInterface1>
。 因此有很多LParentImpl.setChildern
,但你試圖限制它,以便它不會。
您可能想說,參數化ParentInterface1
/ 2
,但我建議盡可能避免接口的多重繼承(而不僅僅是涉及泛型的地方)。
這不是答案,但我要感謝Jorn的回答!
當我試圖完全按照你的答案給我的時候,我偶然發現了這個帖子(雖然它沒有回答原來的提問者)。 我試着這樣做:
public static interface Displayable
extends Identifiable, Nameable { }
public void print(Displayable obj) {
System.out.println("[" + obj.getIdentity() + "] " + obj.getName());
}
這是行不通的,因為我傳遞的對象沒有實現Displayable,但沒有單獨實現Nameable和Identifiable。
使用Jorn的技術,我這樣做:
public <T extends Identifiable & Nameable> void print(T obj) {
System.out.println("[" + obj.getIdentity() + "] " + obj.getName());
}
它完美無瑕!
我希望這對那些遇到與我類似問題的人有所幫助(並且偶然發現了這個問題)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.