Re: [問題] generic type parameter bound?

看板java作者 (sbr)時間16年前 (2009/05/05 07:32), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串7/8 (看更多)
※ 引述《macbuntu (邀怪)》之銘言: : 疑,我沒注意到這個過耶,這樣看 Java parameter type bounds 的規則 : 怎麼變得有點不一致? : class A<T extends Object> { } // OK : class B<T extends Object[]> { } // compile-time error : void func() { : A<? extends Object[]> a; // OK : } : 如果 Java 語法可以准許宣告變數 a 時使用 array type 當作 type bound, : 為什麼要在定義型別 B 時不准使用 array type? : 這是有什麼特別的考量嗎? 上面的例子並不能指出 TypeVariable bounds 可以有 array type,因為 class B 中 TypeParameter: <T extends Object[]> 的 T 是一個 bounded TypeVariable, 而 method func 中的 A<? extends Object[]> 是一個 ParameterizedType 以一個 WildcardType,? extends Object[], 當作 TypeArgument(WildcardType 是 specific type,跟 TypeVariable 無關),因此也沒有規則不一致的情況,畢竟 兩者是不同的東西:一是 TypeVariable (upper)bounds, 一是 WildcardType bound, 前者可以有多個 type (upper)bounds 而後者是 either upperbound or lowerbound 且 type bound 只有一個。 JDT API doc 裡 org.eclipse.jdt.core.dom.TypeParameter - typeBounds method 的內容不是寫錯,我的看法是 1. JDT 的設計本來就是一個 well-formed source code 就可以 build 出語法樹, 儘管裡面有不合格的語法。把一個內容如下的檔案/字串: class B<T extends Object[]> {} 可以由 org.eclipse.jdt.core.dom.ASTParser build 出完整 ASTNode 的樹狀結構, 你可以從其中找出一個 node 是 org.eclipse.jdt.core.dom.TypeParameter object 且其 typeBounds method 傳回的 List 有一個唯一的 element 是 org.eclipse.jdt.cor\ e.dom.ArrayType object。 2. ASTParser 可以直接從 class file(bytecode) build 出 ASTNode tree,那麼 ASTParser 就不應該是只能處理遵守 Java Language spec 的 class bytecode,而是 符合 JVM spec 規範的 class bytecode 皆可。JVM spec 沒有規定 class signature 中的 TypeVariable bounds 不能是 array type。 同樣地,java.lang.reflect.TypeVariable class 的 getBounds method 傳出的 Type[] 也有可能包含代表 array type 的 Type object(java.lang.reflect. GenericArrayType)。 至於為什麼 TypeVariable bounds 不能有 array type,我翻過 JLS v.3 似乎只有 4.9. Intersection Types 一節中的 Discussion 區塊有提到: The form of a bound is restricted (only the first element may be a class or type variable, and only one type variable may appear in the bound) to preclude certain awkward situations coming into existence. However, capture conversion can lead to the creation of type variables whose bounds are more general (e.g., array types). 但沒有明確提供會造成何等 awkward situation 的例子,我目前也沒有想到比較可以 說服自己的例子。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 218.173.140.244
文章代碼(AID): #19_-kYN0 (java)
討論串 (同標題文章)
文章代碼(AID): #19_-kYN0 (java)