“編譯器會進行泛型擦除”是一個常識了(好吧,實際擦除的是參數和自變量的類型)。這個過程由“類型擦除”實現。但是並非像許多開發者認爲的那樣,在 <..> 符號內的東西都被擦除了。看下面這段代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
public
class
ClassTest { public
static
void
main(String[] args) throws
Exception { ParameterizedType
type = (ParameterizedType) Bar. class .getGenericSuperclass(); System.out.println(type.getActualTypeArguments()[ 0 ]); ParameterizedType
fieldType = (ParameterizedType) Foo. class .getField( "children" ).getGenericType(); System.out.println(fieldType.getActualTypeArguments()[ 0 ]); ParameterizedType
paramType = (ParameterizedType) Foo. class .getMethod( "foo" ,
List. class ) .getGenericParameterTypes()[ 0 ]; System.out.println(paramType.getActualTypeArguments()[ 0 ]); System.out.println(Foo. class .getTypeParameters()[ 0 ] .getBounds()[ 0 ]); } class
Foo<E extends
CharSequence> { public
List<Bar> children = new
ArrayList<Bar>(); public
List<StringBuilder> foo(List<String> foo) { return
null ;
} public
void
bar(List<? extends
String> param) {} } class
Bar extends
Foo<String> {} } |
你知道輸出了什麼嗎?
1
2
3
4
5
|
class
java.lang.String class
ClassTest$Bar class
java.lang.String class
java.lang.StringBuilder interface
java.lang.CharSequence |
你會發現每一個類型參數都被保留了,而且在運行期可以通過反射機制獲取到。那麼到底什麼是“類型擦除”?至少某些東西被擦除了吧?是的。事實上,除了結構化信息外的所有東西都被擦除了 —— 這裏結構化信息是指與類結構相關的信息,而不是與程序執行流程有關的。換言之,與類及其字段和方法的類型參數相關的元數據都會被保留下來,可以通過反射獲取到。
而其他的信息都被擦除掉了。例如下面這段代碼:
1
2
3
4
5
|
List<String>
list = new
ArrayList<>(); Iterator<String>
it = list.iterator(); while
(it.hasNext()) { String
s = it.next(); } |
實際上會被轉換成這個(這兩段代碼的字節碼是一致的)
1
2
3
4
5
|
List
list = new
ArrayList(); Iterator
it = list.iterator(); while
(it.hasNext()) { String
s = (String) it.next(); } |
因此,定義在方法體內的類型參數會被擦除,在必要的時候會有類型轉換。另外,如果一個方法被定義爲接受 List 參數,這個 T 會被轉換成 Object (如果定義了類型的上界的話就轉換成對應的類型。這也是你不能 new T() 的原因)。(順便這裏有個關於類型擦除的問題)
目前爲止類型擦除定義中的前兩點我們都講完了。第三點是關於bridge方法,我已經在 stackoverflow 上的這個問題(和回答)中已經說明了。
兩個結論。第一,java 泛型是非常複雜的。但是不用完全理解這些細節也可以使用它們。
第二,不要假設所有的類型信息都被擦除了 —— 結構化的類型參數還存在,需要的話還是可以用下的(不過不要過分依賴反射機制)。