簡體   English   中英

處理清單 <Interface> Java中沒有類型轉換

[英]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>可能不包含適當子類Impl1Impl2所有實例。

唯一(干凈)的方法是使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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM