Java源碼解析(附錄)(5) —— WildcardType

WildcardType 泛型表達式

通配符表達式,泛型表達式,也可以說是,限定性的泛型,形如:? extends classA、?super classB。

源碼

public interface WildcardType extends Type {
    //獲得泛型表達式上界(上限)
    Type[] getUpperBounds();
    //獲得泛型表達式下界(下限)
    Type[] getLowerBounds();
}

概述

WildcardType,通配符表達式,Type子接口,但是在Java中並沒有WildcardType類型,詳見:Type Java類型

源碼詳解

1.getUpperBounds
獲取泛型表達式上界,根據API的註釋提示:現階段通配符表達式僅僅接受一個上邊界或者下邊界,這個和定義類型變量時候可以指定多個上邊界是不一樣。但是API說了,爲了保持擴展性,這裏返回值類型寫成了數組形式。實際上現在返回的數組的大小就是1,通配符?指定多個上邊界或者下邊界現在是會編譯出錯的(jdk1.7是這樣的,至於7及以後就不知道了)。
2.getLowerBounds
獲取泛型表達式下界。

public <T> void test(List<? extends classA > a){}
Method method = Main.class.getMethod("test",List.class);
        Type[] upperBounds = null;
        Type[] lowerBounds = null;
        Type[] types = method.getGenericParameterTypes();
        for(Type type : types){
        Type[] actualTypeArgument = ((ParameterizedType)type).getActualTypeArguments();
            for(Type t : actualTypeArgument){
                WildcardType wildcardType = (WildcardType) t;
                lowerBounds = wildcardType.getLowerBounds();
                upperBounds = wildcardType.getUpperBounds();
                System.out.println("通配符表達式類型是:"+ wildcardType);
                if(upperBounds.length != 0){
                    System.out.println("表達式上邊界:"+Arrays.asList(upperBounds));
                    }
                if(lowerBounds.length != 0){
                    System.out.println("表達式下邊界:"+Arrays.asList(lowerBounds));
                    }
            }
        }
//輸出結果
通配符表達式類型是:? extends com.fcc.test.classA
表達式上邊界:[class com.fcc.test.classA]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章