Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

[Android 拾遺] 善用泛型弱化方法返回值型別

編輯:關於 Android 程式設計

在閱讀 Android 源碼時,常常能從中學到一些優雅的 Java 寫法。本文要分享的是 Bundle 類別中 getParcelable 方法的實作,它巧妙地運用了泛型,讓方法在取回 Parcelable 物件時,不必由呼叫端再做一次 cumbersome 的型別轉換。

原始碼解析

/**
 * Returns the value associated with the given key, or null if
 * no mapping of the desired type exists for the given key or a null
 * value is explicitly associated with the key.
 *
 * @param key a String, or null
 * @return a Parcelable value, or null
 */
public <T extends Parcelable> T getParcelable(String key) {
    unparcel();
    Object o = mMap.get(key);
    if (o == null) {
        return null;
    }
    try {
        return (T) o;
    } catch (ClassCastException e) {
        typeWarning(key, o, "Parcelable", e);
        return null;
    }
}

泛型方法帶來的便利

這個方法最精彩的地方,在於方法簽名宣告了 <T extends Parcelable>,回傳型別也直接使用泛型 T。這意味著呼叫端可以這樣寫:

MyObject obj = bundle.getParcelable("key");

由於編譯器能依據左值自動推斷出型別 T,我們完全不必再手動加上 (MyObject) 的轉型。這正是所謂「弱化方法返回值型別」的精髓——把型別資訊交由呼叫端的上下文來決定,讓程式碼更簡潔、型別更安全。

當然,這背後仍伴隨著一個未檢查的轉型(unchecked cast),所以方法內部特別用 try-catch 包住強制轉型,一旦發生 ClassCastException,就透過 typeWarning 提示開發者,並回傳 null 而非讓程式崩潰。這種既追求簡潔、又兼顧健壯性的設計思路,非常值得我們在自己的專案中借鏡。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved