[英]Handling List<Interface> without type casting in java
想象一下這種情況。
MyInterface{
method1();
method2();
...
}
MyImpl1 implements MyInterface{
...
}
MyImpl2 implements MyInterface{
...
}
SomeOtherClass{
...
public List<MyInterface> foo();
}
Service1{
public List<Impl1> service1Impl(){
SomeOtherClass obj = new SomeOtherClass(...);
return (List<Impl1>)obj.foo()
}
}
Service2{
public List<Impl2> service2Impl(){
SomeOtherClass obj = new SomeOtherClass(...);
return (List<Impl2>)obj.foo()
}
}
SomeOtherClass.java的foo()可以根據在其構造函數中傳遞的參數返回List<MyImpl1>
或List<MyImp2>
。 可以說在Service1中它返回List<Impl1>
,對於Service2類,obj.foo()將返回List<Impl2>
。
我有辦法避免這種顯式類型轉換嗎? 我正在考慮使Service1的foo()方法在返回之前返回List而不是不進行類型轉換的List。
問題是List<MyInterface>
可能不包含適當子類Impl1
或Impl2
所有實例。
唯一(干凈)的方法是使SomeOtherClass
通用:
class SomeOtherClass<T extends MyInterface>{
public List<T> foo();
}
然后:
class Service1 {
public List<Impl1> service1Impl(){
SomeOtherClass<Impl1> obj = new SomeOtherClass<>(...);
return obj.foo();
}
}
class Service2 {
public List<Impl2> service2Impl(){
SomeOtherClass<Impl2> obj = new SomeOtherClass<>(...);
return obj.foo();
}
}
簡短的答案:您不能。
長答案:我們知道,給定方法簽名,就是SomeOtherClass
返回MyInterface
對象的列表。 我們不知道這些對象是什么,無論它們是Impl1
的列表, Impl2
的列表還是其他實現的列表。
為了說明起見,假設SomeOtherClass
返回一個JoesNewImplementation
列表。 你在你施放此service1Impl
到列表Impl1
,然后嘗試獲得一個項目的淘汰之列。 當然會發生ClassCastException
。
理想情況下,這是可以在編譯時捕獲的東西。 您的轉換有效地覆蓋了編譯器提供的安全檢查。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.