原文跳轉鏈接 原文鏈接
引言
泛型是Java中一個非常重要的知識點,在Java集合類框架中泛型被廣泛應用。本文我們將從零開始來看一下Java泛型的設計,將會涉及到通配符處理,以及讓人苦惱的類型擦除。
泛型基礎
泛型類
我們首先定義一個簡單的Box類:
1 2 3 4 5 | public class Box { private String object; public void set(String object) { this .object = object; } public String get() { return object; } } |
這是最常見的做法,這樣做的一個壞處是Box裏面現在只能裝入String類型的元素,今後如果我們需要裝入Integer等其他類型的元素,還必須要另外重寫一個Box,代碼得不到複用,使用泛型可以很好的解決這個問題。
1 2 3 4 5 6 | public class Box<T> { // T stands for "Type" private T t; public void set(T t) { this .t = t; } public T get() { return t; } } |
這樣我們的Box
類便可以得到複用,我們可以將T替換成任何我們想要的類型:
1 2 3 | Box<Integer> integerBox = new Box<Integer>(); Box<Double> doubleBox = new Box<Double>(); Box<String> stringBox = new Box<String>(); |
泛型方法
看完了泛型類,接下來我們來了解一下泛型方法。聲明一個泛型方法很簡單,只要在返回類型前面加上一個類似<K, V>
的形式就行了:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public class Util { public static <K, V> boolean compare(Pair<K, V> p1, Pair<K, V> p2) { return p1.getKey().equals(p2.getKey()) && p1.getValue().equals(p2.getValue()); } } public class Pair<K, V> { private K key; private V value; public Pair(K key, V value) { this .key = key; this .value = value; } public void setKey(K key) { this .key = key; } public void setValue(V value) { this .value = value; } public K getKey() { return key; } public V getValue() { return value; } } |
我們可以像下面這樣去調用泛型方法:
1 2 3 | Pair<Integer, String> p1 = new Pair<>( 1 , "apple" ); Pair<Integer, String> p2 = new Pair<>( 2 , "pear" ); boolean same = Util.<Integer, String>compare(p1, p2); |
或者在Java1.7/1.8利用type inference,讓Java自動推導出相應的類型參數:
1 2 3 | Pair<Integer, String> p1 = new Pair<>( 1 , "apple" ); Pair<Integer, String> p2 = new Pair<>( 2 , "pear" ); boolean same = Util.compare(p1, p2); |
邊界符
現在我們要實現這樣一個功能,查找一個泛型數組中大於某個特定元素的個數,我們可以這樣實現:
1 2 3 4 5 6 7 | public static <T> int countGreaterThan(T[] anArray, T elem) { int count = 0 ; for (T e : anArray) if (e > elem) // compiler error ++count; return count; } |
但是這樣很明顯是錯誤的,因爲除了short, int, double, long, float, byte, char
等原始類型,其他的類並不一定能使用操作符>
,所以編譯器報錯,那怎麼解決這個問題呢?答案是使用邊界符。
1 2 3 | public interface Comparable<T> { public int compareTo(T o); } |
做一個類似於下面這樣的聲明,這樣就等於告訴編譯器類型參數T
代表的都是實現了Comparable
接口的類,這樣等於告訴編譯器它們都至少實現了compareTo
方法。
1 2 3 4 5 6 7 | public static <T extends Comparable<T>> int countGreaterThan(T[] anArray, T elem) { int count = 0 ; for (T e : anArray) if (e.compareTo(elem) > 0 ) ++count; return count; } |
通配符
在瞭解通配符之前,我們首先必須要澄清一個概念,還是借用我們上面定義的Box類,假設我們添加一個這樣的方法:
1 | public void boxTest(Box<Number> n) { /* ... */ } |
那麼現在Box<Number> n
允許接受什麼類型的參數?我們是否能夠傳入Box<Integer>
或者Box<Double>
呢?答案是否定的,雖然Integer和Double是Number的子類,但是在泛型中Box<Integer>
或者Box<Double>
與Box<Number>
之間並沒有任何的關係。這一點非常重要,接下來我們通過一個完整的例子來加深一下理解。
首先我們先定義幾個簡單的類,下面我們將用到它:
1 2 3 | class Fruit {} class Apple extends Fruit {} class Orange extends Fruit {} |
下面這個例子中,我們創建了一個泛型類Reader
,然後在f1()
中當我們嘗試Fruit f = fruitReader.readExact(apples);
編譯器會報錯,因爲List<Fruit>
與List<Apple>
之間並沒有任何的關係。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public class GenericReading { static List<Apple> apples = Arrays.asList( new Apple()); static List<Fruit> fruit = Arrays.asList( new Fruit()); static class Reader<T> { T readExact(List<T> list) { return list.get( 0 ); } } static void f1() { Reader<Fruit> fruitReader = new Reader<Fruit>(); // Errors: List<Fruit> cannot be applied to List<Apple>. // Fruit f = fruitReader.readExact(apples); } public static void main(String[] args) { f1(); } } |
但是按照我們通常的思維習慣,Apple和Fruit之間肯定是存在聯繫,然而編譯器卻無法識別,那怎麼在泛型代碼中解決這個問題呢?我們可以通過使用通配符來解決這個問題:
1 2 3 4 5 6 7 8 9 10 11 12 13 | static class CovariantReader<T> { T readCovariant(List<? extends T> list) { return list.get( 0 ); } } static void f2() { CovariantReader<Fruit> fruitReader = new CovariantReader<Fruit>(); Fruit f = fruitReader.readCovariant(fruit); Fruit a = fruitReader.readCovariant(apples); } public static void main(String[] args) { f2(); } |
這樣就相當與告訴編譯器, fruitReader的readCovariant方法接受的參數只要是滿足Fruit的子類就行(包括Fruit自身),這樣子類和父類之間的關係也就關聯上了。
PECS原則
上面我們看到了類似<? extends T>
的用法,利用它我們可以從list裏面get元素,那麼我們可不可以往list裏面add元素呢?我們來嘗試一下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public class GenericsAndCovariance { public static void main(String[] args) { // Wildcards allow covariance: List<? extends Fruit> flist = new ArrayList<Apple>(); // Compile Error: can't add any type of object: // flist.add(new Apple()) // flist.add(new Orange()) // flist.add(new Fruit()) // flist.add(new Object()) flist.add( null ); // Legal but uninteresting // We Know that it returns at least Fruit: Fruit f = flist.get( 0 ); } } |
答案是否定,Java編譯器不允許我們這樣做,爲什麼呢?對於這個問題我們不妨從編譯器的角度去考慮。因爲List<? extends Fruit> flist
它自身可以有多種含義:
1 2 3 | List<? extends Fruit> flist = new ArrayList<Fruit>(); List<? extends Fruit> flist = new ArrayList<Apple>(); List<? extends Fruit> flist = new ArrayList<Orange>(); |
- 當我們嘗試add一個Apple的時候,flist可能指向
new ArrayList<Orange>()
; - 當我們嘗試add一個Orange的時候,flist可能指向
new ArrayList<Apple>()
; - 當我們嘗試add一個Fruit的時候,這個Fruit可以是任何類型的Fruit,而flist可能只想某種特定類型的Fruit,編譯器無法識別所以會報錯。
所以對於實現了<? extends T>
的集合類只能將它視爲Producer向外提供(get)元素,而不能作爲Consumer來對外獲取(add)元素。
如果我們要add元素應該怎麼做呢?可以使用<? super T>
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public class GenericWriting { static List<Apple> apples = new ArrayList<Apple>(); static List<Fruit> fruit = new ArrayList<Fruit>(); static <T> void writeExact(List<T> list, T item) { list.add(item); } static void f1() { writeExact(apples, new Apple()); writeExact(fruit, new Apple()); } static <T> void writeWithWildcard(List<? super T> list, T item) { list.add(item) } static void f2() { writeWithWildcard(apples, new Apple()); writeWithWildcard(fruit, new Apple()); } public static void main(String[] args) { f1(); f2(); } } |
這樣我們可以往容器裏面添加元素了,但是使用super的壞處是以後不能get容器裏面的元素了,原因很簡單,我們繼續從編譯器的角度考慮這個問題,對於List<? super Apple> list
,它可以有下面幾種含義:
1 2 3 | List<? super Apple> list = new ArrayList<Apple>(); List<? super Apple> list = new ArrayList<Fruit>(); List<? super Apple> list = new ArrayList<Object>(); |
當我們嘗試通過list來get一個Apple的時候,可能會get得到一個Fruit,這個Fruit可以是Orange等其他類型的Fruit。
根據上面的例子,我們可以總結出一條規律,”Producer Extends, Consumer Super”:
- “Producer Extends” – 如果你需要一個只讀List,用它來produce T,那麼使用
? extends T
。 - “Consumer Super” – 如果你需要一個只寫List,用它來consume T,那麼使用
? super T
。 - 如果需要同時讀取以及寫入,那麼我們就不能使用通配符了。
如何閱讀過一些Java集合類的源碼,可以發現通常我們會將兩者結合起來一起用,比如像下面這樣:
1 2 3 4 5 6 | public class Collections { public static <T> void copy(List<? super T> dest, List<? extends T> src) { for ( int i= 0 ; i<src.size(); i++) dest.set(i, src.get(i)); } } |
類型擦除
Java泛型中最令人苦惱的地方或許就是類型擦除了,特別是對於有C++經驗的程序員。類型擦除就是說Java泛型只能用於在編譯期間的靜態類型檢查,然後編譯器生成的代碼會擦除相應的類型信息,這樣到了運行期間實際上JVM根本就知道泛型所代表的具體類型。這樣做的目的是因爲Java泛型是1.5之後才被引入的,爲了保持向下的兼容性,所以只能做類型擦除來兼容以前的非泛型代碼。對於這一點,如果閱讀Java集合框架的源碼,可以發現有些類其實並不支持泛型。
說了這麼多,那麼泛型擦除到底是什麼意思呢?我們先來看一下下面這個簡單的例子:
1 2 3 4 5 6 7 8 9 10 | public class Node<T> { private T data; private Node<T> next; public Node(T data, Node<T> next) { this .data = data; this .next = next; } public T getData() { return data; } // ... } |
編譯器做完相應的類型檢查之後,實際上到了運行期間上面這段代碼實際上將轉換成:
1 2 3 4 5 6 7 8 9 10 | public class Node { private Object data; private Node next; public Node(Object data, Node next) { this .data = data; this .next = next; } public Object getData() { return data; } // ... } |
這意味着不管我們聲明Node<String>
還是Node<Integer>
,到了運行期間,JVM統統視爲Node<Object>
。有沒有什麼辦法可以解決這個問題呢?這就需要我們自己重新設置bounds了,將上面的代碼修改成下面這樣:
1 2 3 4 5 6 7 8 9 10 | public class Node<T extends Comparable<T>> { private T data; private Node<T> next; public Node(T data, Node<T> next) { this .data = data; this .next = next; } public T getData() { return data; } // ... } |
這樣編譯器就會將T
出現的地方替換成Comparable
而不再是默認的Object
了:
1 2 3 4 5 6 7 8 9 10 | public class Node { private Comparable data; private Node next; public Node(Comparable data, Node next) { this .data = data; this .next = next; } public Comparable getData() { return data; } // ... } |
上面的概念或許還是比較好理解,但其實泛型擦除帶來的問題遠遠不止這些,接下來我們系統地來看一下類型擦除所帶來的一些問題,有些問題在C++的泛型中可能不會遇見,但是在Java中卻需要格外小心。
問題一
在Java中不允許創建泛型數組,類似下面這樣的做法編譯器會報錯:
1 | List<Integer>[] arrayOfLists = new List<Integer>[ 2 ]; // compile-time error |
爲什麼編譯器不支持上面這樣的做法呢?繼續使用逆向思維,我們站在編譯器的角度來考慮這個問題。
我們先來看一下下面這個例子:
1 2 3 | Object[] strings = new String[ 2 ]; strings[ 0 ] = "hi" ; // OK strings[ 1 ] = 100 ; // An ArrayStoreException is thrown. |
對於上面這段代碼還是很好理解,字符串數組不能存放整型元素,而且這樣的錯誤往往要等到代碼運行的時候才能發現,編譯器是無法識別的。接下來我們再來看一下假設Java支持泛型數組的創建會出現什麼後果:
1 2 3 4 | Object[] stringLists = new List<String>[]; // compiler error, but pretend it's allowed stringLists[ 0 ] = new ArrayList<String>(); // OK // An ArrayStoreException should be thrown, but the runtime can't detect it. stringLists[ 1 ] = new ArrayList<Integer>(); |
假設我們支持泛型數組的創建,由於運行時期類型信息已經被擦除,JVM實際上根本就不知道new ArrayList<String>()
和new ArrayList<Integer>()
的區別。類似這樣的錯誤假如出現才實際的應用場景中,將非常難以察覺。
如果你對上面這一點還抱有懷疑的話,可以嘗試運行下面這段代碼:
1 2 3 4 5 6 7 | public class ErasedTypeEquivalence { public static void main(String[] args) { Class c1 = new ArrayList<String>().getClass(); Class c2 = new ArrayList<Integer>().getClass(); System.out.println(c1 == c2); // true } } |
問題二
繼續複用我們上面的Node
的類,對於泛型代碼,Java編譯器實際上還會偷偷幫我們實現一個Bridge method。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public class Node<T> { public T data; public Node(T data) { this .data = data; } public void setData(T data) { System.out.println( "Node.setData" ); this .data = data; } } public class MyNode extends Node<Integer> { public MyNode(Integer data) { super (data); } public void setData(Integer data) { System.out.println( "MyNode.setData" ); super .setData(data); } } |
看完上面的分析之後,你可能會認爲在類型擦除後,編譯器會將Node和MyNode變成下面這樣:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public class Node { public Object data; public Node(Object data) { this .data = data; } public void setData(Object data) { System.out.println( "Node.setData" ); this .data = data; } } public class MyNode extends Node { public MyNode(Integer data) { super (data); } public void setData(Integer data) { System.out.println( "MyNode.setData" ); super .setData(data); } } |
實際上不是這樣的,我們先來看一下下面這段代碼,這段代碼運行的時候會拋出ClassCastException
異常,提示String無法轉換成Integer:
1 2 3 4 | MyNode mn = new MyNode( 5 ); Node n = mn; // A raw type - compiler throws an unchecked warning n.setData( "Hello" ); // Causes a ClassCastException to be thrown. // Integer x = mn.data; |
如果按照我們上面生成的代碼,運行到第3行的時候不應該報錯(注意我註釋掉了第4行),因爲MyNode中不存在setData(String data)
方法,所以只能調用父類Node的setData(Object data)
方法,既然這樣上面的第3行代碼不應該報錯,因爲String當然可以轉換成Object了,那ClassCastException
到底是怎麼拋出的?
實際上Java編譯器對上面代碼自動還做了一個處理:
1 2 3 4 5 6 7 8 9 10 11 | class MyNode extends Node { // Bridge method generated by the compiler public void setData(Object data) { setData((Integer) data); } public void setData(Integer data) { System.out.println( "MyNode.setData" ); super .setData(data); } // ... } |
這也就是爲什麼上面會報錯的原因了,setData((Integer) data);
的時候String無法轉換成Integer。所以上面第2行編譯器提示unchecked warning
的時候,我們不能選擇忽略,不然要等到運行期間才能發現異常。如果我們一開始加上Node<Integer> n = mn
就好了,這樣編譯器就可以提前幫我們發現錯誤。
問題三
正如我們上面提到的,Java泛型很大程度上只能提供靜態類型檢查,然後類型的信息就會被擦除,所以像下面這樣利用類型參數創建實例的做法編譯器不會通過:
1 2 3 4 | public static <E> void append(List<E> list) { E elem = new E(); // compile-time error list.add(elem); } |
但是如果某些場景我們想要需要利用類型參數創建實例,我們應該怎麼做呢?可以利用反射解決這個問題:
1 2 3 4 | public static <E> void append(List<E> list, Class<E> cls) throws Exception { E elem = cls.newInstance(); // OK list.add(elem); } |
我們可以像下面這樣調用:
1 2 | List<String> ls = new ArrayList<>(); append(ls, String. class ); |
實際上對於上面這個問題,還可以採用Factory和Template兩種設計模式解決,感興趣的朋友不妨去看一下Thinking in Java中第15章中關於Creating instance of types(英文版第664頁)的講解,這裏我們就不深入了。
問題四
我們無法對泛型代碼直接使用instanceof
關鍵字,因爲Java編譯器在生成代碼的時候會擦除所有相關泛型的類型信息,正如我們上面驗證過的JVM在運行時期無法識別出ArrayList<Integer>
和ArrayList<String>
的之間的區別:
1 2 3 4 5 6 | public static <E> void rtti(List<E> list) { if (list instanceof ArrayList<Integer>) { // compile-time error // ... } } => { ArrayList<Integer>, ArrayList<String>, LinkedList<Character>, ... } |
和上面一樣,我們可以使用通配符重新設置bounds來解決這個問題:
1 2 3 4 5 | public static void rtti(List<?> list) { if (list instanceof ArrayList<?>) { // OK; instanceof requires a reifiable type // ... } } |
工廠模式
接下來我們利用泛型來簡單的實現一下工廠模式,首先我們先聲明一個接口Factory
:
1 2 3 4 | package typeinfo.factory; public interface Factory<T> { T create(); } |
接下來我們來創建幾個實體類FuelFilter
和AirFilter
以及FanBelt
和GeneratorBelt
。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class Filter extends Part {} class FuelFilter extends Filter { public static class Factory implements typeinfo.factory.Factory<FuelFilter> { public FuelFilter create() { return new FuelFilter(); } } } class AirFilter extends Filter { public static class Factory implements typeinfo.factory.Factory<AirFilter> { public AirFilter create() { return new AirFilter(); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class Belt extends Part {} class FanBelt extends Belt { public static class Factory implements typeinfo.factory.Factory<FanBelt> { public FanBelt create() { return new FanBelt(); } } } class GeneratorBelt extends Belt { public static class Factory implements typeinfo.factory.Factory<GeneratorBelt> { public GeneratorBelt create() { return new GeneratorBelt(); } } } |
Part
類的實現如下,注意我們上面的實體類都是Part
類的間接子類。在Part類我們註冊
了我們上面的聲明的實體類。所以以後我們如果要創建相關的實體類的話,只需要在調用Part類的相關方法了。這麼做的一個好處就是如果的業務中出現了CabinAirFilter
或者PowerSteeringBelt
的話,我們不需要修改太多的代碼,只需要在Part類中將它們註冊即可。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class Part { static List<Factory<? extends Part>> partFactories = new ArrayList<Factory<? extends Part>>(); static { partFactories.add( new FuelFilter.Factory()); partFactories.add( new AirFilter.Factory()); partFactories.add( new FanBelt.Factory()); partFactories.add( new PowerSteeringBelt.Factory()); } private static Random rand = new Random( 47 ); public static Part createRandom() { int n = rand.nextInt(partFactories.size()); return partFactories.get(n).create(); } public String toString() { return getClass().getSimpleName(); } } |
最後我們來測試一下:
1 2 3 4 5 6 7 | public class RegisteredFactories { public static void main(String[] args) { for ( int i = 0 ; i < 10 ; i++) { System.out.println(Part.createRandom()); } } } |