Skip to content
Rain Hu's Workspace
Go back

[Java] Java 的中 HashMap.comparableClassFor(Object x) 的函式解讀

Rain Hu

HashMap.comparableClassFor(Object x) 的函式解讀

原文敘述
Returns x’s Class if it is of the form “class C implements Comparable”, else null.

我的翻譯 當x的類別為Comparable的實作時,返回x的類別;否則返回 null。

Source Code

static Class<?> comparableClassFor(Object x) {
    if (x instanceof Comparable) {
        Class<?> c; Type[] ts, as; ParameterizedType p;
        if ((c = x.getClass()) == String.class) // bypass checks
            return c;
        if ((ts = c.getGenericInterfaces()) != null) {
            for (Type t : ts) {
                if ((t instanceof ParameterizedType) &&
                    ((p = (ParameterizedType) t).getRawType() ==
                        Comparable.class) &&
                    (as = p.getActualTypeArguments()) != null &&
                    as.length == 1 && as[0] == c) // type arg is c
                    return c;
            }
        }
    }
    return null;
}

instanceof

getClass()

getGenericInterfaces()

getGenericSuperclass()和getSuperclass()

這兩個函式雖然沒有出現在 comparableClassFor(Object x)中,但也順帶一提。

ParameterizedType

getRawType()

getActualTypeArguments()

getOwnerType()

comparableClassFor(Object x) 總結

static Class<?> comparableClassFor(Object x) {
    if (x instanceof Comparable) { // 判斷是否實作了 Comparable 介面
        Class<?> c; Type[] ts, as; ParameterizedType p;
        if ((c = x.getClass()) == String.class) // 如果是String類別,直接返回String.class
            return c;
        if ((ts = c.getGenericInterfaces()) != null) { // 檢查是否有直接實現的介面
            for (Type t : ts) {    // 遍歷介面
                if ((t instanceof ParameterizedType) &&      // 當介面實現了泛型
                    ((p = (ParameterizedType) t).getRawType() ==    // 取得介面不帶參數時的類別對象
                        Comparable.class) &&                        // 且為 Comparable
                    (as = p.getActualTypeArguments()) != null &&    // 取得該介面的泛型參數
                    as.length == 1 && as[0] == c) // type arg is c  // 只帶有一種泛型且是實作類別為其本身
                    return c;    // 返回該類別
            }
        }
    }
    return null;    // 皆否則回傳 null
}

Share this post on:

Previous
[Java] Integer.bitCount 解析
Next
[Device] Ring Oscillator 環形振盪器