標籤:ble getc java pes 理解 聯合 xtend 必須 types
前言
Union Type和Intersection Type都是將多個類型結合起來的一個等價的“類型”,它們並非是實際存在的類型。
Union Type
Union type(等位型別)使用位元或運算子|進行構造:
A | B | C
注意:用|符號來構造Union Type類型只是Java語言的規定,|在這裡不代表位元或的含義。
上例中,A | B | C是一個Union type,Union 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,它兼具MyA和MyB的特徵,因此可以將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