Class.asSubclass淺談

來源:互聯網
上載者:User
  1. public <U> Class<? extends U> asSubclass(Class<U> clazz)  

這是java.lang.Class中的一個方法,作用是將調用這個方法的class對象轉換成由clazz參數所表示的class對象的某個子類。舉例來說,

  1. List<String> strList = new ArrayList<String>();  
  2. Class<? extends List> strList_cast = strList.getClass().asSubclass(List.class);  

 上面的代碼將strList.getClass()擷取的class對象轉換成Class<? extends List>,這麼做似乎沒有什麼意義,因為我們很清楚strList.getClass()擷取的class對象就是ArrayList,它當然是List.class的一個子類;

但有些情況下,我們並不能確知一個class對象的類型,典型的情況是Class.forName()擷取的class對象:

 

Class.forName()的傳回型別是Class<?>,但這顯然太寬泛了,假設我們需要List.class類型的class對象,但我們傳遞給Class.forName的參數是未知的(可能是"java.lang.String",也可能是"java.util.ArrayList"),這時我們就可以用到asSubclass()這個方法了,如下:

  1. Class.forName("xxx.xxx.xxx").asSubclass(List.class).newInstance();  

 當xxx.xxx.xxx是List的子類時,正常執行,當不是List的子類時,拋出ClassCastException,這時我們可以做些別的處理;

 

如果我們查看Class.asSubclass()在JDK中的中的引用的話,會發現這種用法有很多。

 

這裡有必要說下 instanceof 關鍵字.

  1. <<object reference>> instanceof <<class/interface name>>  

它的用法用於判斷一個Object是否是某個超類或者介面的一個子類或者實作類別(不一定是直接超類或者直接介面),如下

  1. interface IFace {  
  2.       
  3. }  
  4.   
  5. class IFaceImpl implements IFace {  
  6.       
  7. }  
  8.   
  9. class IFaceImplExt extends IFaceImpl {  
  10.       
  11. }  
  12.   
  13. System.out.println(new IFaceImpl() instanceof IFace); // true  
  14. System.out.println(new IFaceImplExt() instanceof IFace); // true  

asSubclass用於窄化未知的Class類型的範圍,而instanceof用於判斷一個對象引用是否是一個超類或者介面的子類/實作類別,如果試圖將instanceof用於Class類型的判斷會引起編譯錯誤。

  1. // both will cause compliration error  
  2. System.out.println(IFaceImpl.class instanceof IFace);  
  3. System.out.println(IFaceImplExt.class instanceof IFace.class);  

 

轉載:http://jasonhan-sh-hotmail-com.iteye.com/blog/1838413

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.