java基礎之反射類型TypeJava在加入泛型之后,僅僅Class已經不足以描述數(shù)據的類型了,比如List類型的數(shù)據,其Class的類型為List.class,但是其類型包含了泛型參數(shù),所以java引入了Type類型來描述泛型類型。除了泛型類型,還有數(shù)組格式的數(shù)據,其類型也包含兩部分,一部分是數(shù)組對象本身的class,另外一部分是數(shù)組中數(shù)據的類型。本文會詳細介紹JavaType中的各種類型,分析這些類型的使用方法。 Type介紹Type是Java 編程語言中所有類型的公共高級接口,也就是Java中所有"類型"的接口。官方原話定義如下 這樣的官方描述有點難懂,此處我畫個圖解釋一下。Type其實是和泛型一起出現(xiàn)的,可以說Type就是為了支持泛型。
> A type variable is an unqualified identifier used as a type in class, interface, method, and constructor bodies. Type的類型Type可以分為兩大類:包含TypeVariables和不包含TypeVariables的類型:
繼續(xù)介紹Type之前,需要先介紹一下java的泛型機制: 泛型是Java SE 1.5的新特性,泛型的本質是參數(shù)化類型,也就是說所操作的數(shù)據類型被指定為一個參數(shù)。這種參數(shù)類型可以用在類、接口和方法的創(chuàng)建中,分別稱為泛型類、泛型接口、泛型方法。 Java語言引入泛型的好處是安全簡單。泛型的好處是在編譯的時候檢查類型安全,并且所有的強制轉換都是自動和隱式的,以提高代碼的重用率。 泛型信息只存在于代碼編譯階段,在進入 JVM 之前,與泛型相關的信息會被擦除掉,專業(yè)術語叫做類型擦除。 參數(shù)化類型ParameterizedType參數(shù)化類型的寫法如下:C,其中C是Class類型, 是Type,先列幾個參數(shù)化類型的合法定義: Seq\<string\> seq\<seq\<string\>\>="" seq\<string\>.zipper\<integer\>="" pair\<string,integer\>="" ParameterizedType類型的接口方法介紹: >ParameterizedType represents a parameterized type such as Collection.A parameterized type is created the first time it is needed by a reflective method, as specified in this package. When a parameterized type p is created, the generic type declaration that p instantiates is resolved, and all type arguments of p are created recursively. See TypeVariable for details on the creation process for type variables. Repeated creation of a parameterized type has no effect. Instances of classes that implement this interface must implement an equals() method that equates any two instances that share the same generic type declaration and have equal type parameters. 數(shù)組泛型類型的寫法如下:C[],其中C是Class類型, 是Type,先列幾個數(shù)組泛型類型的合法定義: 注意:<>不能出現(xiàn)在數(shù)組的初始化中,即new數(shù)組之后不能出現(xiàn)<>,否則javac無法通過。但是作為引用變量或者方法的某個參數(shù)是完全可以的。不包含泛型的數(shù)組本節(jié)不做介紹(如String[]),下文中會進行介紹。 通配符類型何其字面意思相同,其泛型類型不再是一個具體的類,而是一個通配符表達式,表達式包含以下三種:"?","? extends Type", "? super Type",其中Type可以為WildcardType,GenericArrayType,ParameterizedType,Class. WildcardType 接口的方法和介紹如下. 通過反射獲取基本的Class和基本數(shù)據類型此處就不詳細介紹了,接下來會重點介紹一下數(shù)組類型。java的數(shù)組類型由虛擬機生成,虛擬機生成的數(shù)組類型的名稱一般類似于"class [[Ljava.lang.String;",注意其中的"[["表示是二維數(shù)組。那么如何獲取數(shù)組中的元素類型呢? java.lang.Class包中提供了以下接口查詢: >componentType():Returns the component type of this Class, if it describes an array type, or null otherwise. 平時使用java程序的過程中,我們接觸到的最多的類型只有Class,像泛型類型和數(shù)組類型,通常只有通過反射才能獲取到。 如下程序中,我們首先定義了一個自定義的類TestParameterizedType,只包含一個字段List field,然后我們在另外一個單測實例中嘗試通過反射獲取field的相關信息。通過field.getType()我們獲取到了field的類型。通過field.getGenericType()我們獲取到了field的泛型信息。 類似于字段的獲取方式,方法可以通過 不可能,具體原因參考java的泛型擦除原理。 本文大多數(shù)內容參考了java官方文檔,點此直達JAVA15官方文檔地址
|
|