Java中的Union Types和Intersection Types

來源:互聯網
上載者:User

標籤:ble   getc   java   pes   理解   聯合   xtend   必須   types   

前言

Union TypeIntersection Type都是將多個類型結合起來的一個等價的“類型”,它們並非是實際存在的類型。

Union Type

Union type(等位型別)使用位元或運算子|進行構造:

A | B | C

注意:|符號來構造Union Type類型只是Java語言的規定,|在這裡不代表位元或的含義。

上例中,A | B | C是一個Union typeUnion type的含義就是“或”只要滿足其中一個即可

執行個體:捕獲多個異常中的一個
try {    // ...} catch (ExceptionA | ExceptionB e) {    } 

就等價於:

try {    // ...} catch (ExceptionA e) {    } catch (ExceptionB e) {    }
Intersection Type

Intersection type(交集類型)使用位元與運算子&進行:

A & B & C

Intersection type(交集類型),雖然名稱翻譯過來是“交集”,但是Intersection type並非數學上的交集含義。A & B & C的含義是:該交集類型兼具A、B、C的特徵,相當於把A、B、C中每一個的相關成員都繼承過來了

注意:Type1 & Type2 & Type3 & ... & Type n中,必須滿足:至少有n-1個介面,如果有1個類必須放在一開始。

執行個體1:泛型類
class MyA {}interface MyB {}class Combination extends MyA implements MyB {}class MyC<T extends MyA & MyB> {}public class Test {    public static void main(String[] args) {        // new MyC<MyA & MyB>(); 報錯, <>內不能用Intersection Type        new MyC<Combination>(); // OK    }}

如何理解<T extends MyA & MyB>呢?可以將MyA & MyB等價為一個類型U,它兼具MyAMyB的特徵,因此可以將Combanation類作為MyC的型別參數。

執行個體2:對Lambda運算式進行強制類型轉換
public class Test {    public static void main(String[] args) {        Runnable job =(Runnable & Serializable) () ->System.out.println("Hello");        Class[] interfaces = job.getClass().getInterfaces();        for (Class i : interfaces) {            System.out.println(i.getSimpleName());        }    }}/*RunnableSerializable

Java中的Union Types和Intersection Types

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.