Gson通過藉助TypeToken獲取泛型參數的類型的方法


最近在使用Google的Gson包進行Json和Java對象之間的轉化,對於包含泛型的類的序列化和反序列化Gson也提供了很好的支持,感覺有點意思,就花時間研究了一下。

由於Java泛型的實現機制,使用了泛型的代碼在運行期間相關的泛型參數的類型會被擦除,我們無法在運行期間獲知泛型參數的具體類型(所有的泛型類型在運行時都是Object類型)。

但是有的時候,我們確實需要獲知泛型參數的類型,比如將使用了泛型的Java代碼序列化或者反序列化的時候,這個時候問題就變得比較棘手。

 

  1. class Foo<T> {  
  2.   T value;  
  3. }  
  4. Gson gson = new Gson();  
  5. Foo<Bar> foo = new Foo<Bar>();  
  6. gson.toJson(foo); // May not serialize foo.value correctly  
  7.  
  8. gson.fromJson(json, foo.getClass()); // Fails to deserialize foo.value as Bar  
  9.  

 對於上面的類Foo<T>,由於在運行期間無法得知T的具體類型,對這個類的對象進行序列化和反序列化都不能正常進行。Gson通過藉助TypeToken類來解決這個問題。

 

  1. TestGeneric<String> t = new TestGeneric<String>();  
  2.   t.setValue("Alo");  
  3.   Type type = new TypeToken<TestGeneric<String>>(){}.getType();  
  4.     
  5.   String gStr = GsonUtils.gson.toJson(t,type);  
  6.   System.out.println(gStr);  
  7.   TestGeneric t1 = GsonUtils.gson.fromJson(gStr, type);  
  8.   System.out.println(t1.getValue());  

 

 TypeToken的使用非常簡單,如上面的代碼,只要將需要獲取類型的泛型類作爲TypeToken的泛型參數構造一個匿名的子類,就可以通過getType()方法獲取到我們使用的泛型類的泛型參數類型。

下面來簡單分析一下原理。

要獲取泛型參數的類型,一般的做法是在使用了泛型的類的構造函數中顯示地傳入泛型類的Class類型作爲這個泛型類的私有屬性,它保存了泛型類的類型信息。

  1.  public class Foo<T>{  
  2.    
  3.  public Class<T> kind;  
  4.    
  5.  public Foo(Class<T> clazz){  
  6.   this.kind = clazz;  
  7.  }  
  8.    
  9.  public T[] getInstance(){  
  10.   return (T[])Array.newInstance(kind, 5);  
  11.  }  
  12.    
  13.  public static void main(String[] args){  
  14.   Foo<String> foo = new Foo(String.class);  
  15.   String[] strArray = foo.getInstance();  
  16.  }  
  17.  
  18. }  
  19.  

 這種方法雖然能解決問題,但是每次都要傳入一個Class類參數,顯得比較麻煩。Gson庫裏面對於這個問題採用了了另一種解決辦法。

同樣是爲了獲取Class的類型,可以通過另一種方式實現:

 

  1. public abstract class Foo<T>{  
  2.    
  3.  Class<T> type;  
  4.    
  5.  public Foo(){  
  6.   this.type = (Class<T>) getClass();  
  7.  }  
  8.  
  9.         public static void main(String[] args) {  
  10.     
  11.   Foo<String> foo = new Foo<String>(){};  
  12.   Class mySuperClass = foo.getClass();  
  13.  
  14.  }  
  15.    
  16. }  
  17.  

 
 

 

聲明一個抽象的父類Foo,匿名子類將泛型類作爲Foo的泛型參數傳入構造一個實例,再調用getClass方法獲得這個子類的Class類型。

這裏雖然通過另一種方式獲得了匿名子類的Class類型,但是並沒有直接將泛型參數T的Class類型傳進來,那又是如何獲得泛型參數的類型的呢,這要依賴Java的Class字節碼中存儲的泛型參數信息。Java的泛型機制雖然在運行期間泛型類和非泛型類都相同,但是在編譯java源代碼成class文件中還是保存了泛型相關的信息,這些信息被保存在class字節碼常量池中,使用了泛型的代碼處會生成一個signature簽名字段,通過簽名signature字段指明這個常量池的地址。

關於class文件中存儲泛型參數類型的具體的詳細的知識可以參考這裏:http://stackoverflow.com/questions/937933/where-are-generic-types-stored-in-java-class-files

JDK裏面提供了方法去讀取這些泛型信息的方法,再借助反射,就可以獲得泛型參數的具體類型。同樣是對於第一段代碼中的foo對象,通過下面的代碼可以得到foo<T>中的T的類型:

 

  1. Type mySuperClass = foo.getClass().getGenericSuperclass();  
  2. Type type = ((ParameterizedType)mySuperClass).getActualTypeArguments()[0];  
  3. System.out.println(type);  

 

 

       
運行結果是class java.lang.String。

分析一下這段代碼,Class類的getGenericSuperClass()方法的註釋是:

Returns the Type representing the direct superclass of the entity (class, interface, primitive type or void) represented by thisClass.

If the superclass is a parameterized type, the Type object returned must accurately reflect the actual type parameters used in the source code. The parameterized type representing the superclass is created if it had not been created before. See the declaration of ParameterizedType for the semantics of the creation process for parameterized types. If thisClass represents either theObject class, an interface, a primitive type, or void, then null is returned. If this object represents an array class then theClass object representing theObject class is returned

概括來說就是對於帶有泛型的class,返回一個ParameterizedType對象,對於Object、接口和原始類型返回null,對於數組class則是返回Object.class。ParameterizedType是表示帶有泛型參數的類型的Java類型,JDK1.5引入了泛型之後,Java中所有的Class都實現了Type接口,ParameterizedType則是繼承了Type接口,所有包含泛型的Class類都會實現這個接口。

實際運用中還要考慮比較多的情況,比如獲得泛型參數的個數避免數組越界等,具體可以參看Gson中的TypeToken類及ParameterizedTypeImpl類的代碼。

轉自:http://www.ishang123.com/jishubowen/java/2012-07-28/100.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章