本文介紹了為什么不能分配 I <?擴展類型>到<類型>?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
以下陳述:
URLClassLoader ucl = (URLClassLoader) ClassLoader.getSystemClassLoader();
Class<URLClassLoader> uclc = ucl.getClass();
因錯誤而失敗:
Type mismatch: cannot convert from Class<capture#2-of ? extends URLClassLoader> to Class<URLClassLoader>
這里為什么需要演員表?
Why do I need a cast, here?
我發現了幾篇文章解釋了為什么你不能做相反的事情(將 T 分配給 a ),但這(有點)顯而易見并且可以理解.
I found several posts explaining why You can't do the reverse (assign T to a ), but that's (kind of) obvious and understood.
注意:我是在 eclipse Luna 下編寫的,所以我不知道這是 Luna 的怪癖還是我真的不理解泛型.
NOTE: I am coding this under eclipse Luna, so I don't know if it's a Luna Quirk or if there's something I really dont understand in generics.
推薦答案
協變 vs 逆變 vs 不變
類 是不變的.
因此,
類 不是
Class<URLClassLoader>
在 Java 中,變量可以保存對相同類型或子類型的實例的引用.
In Java a variable can hold a reference of an instance of same type or subtype.
因此,
Class<URLClassLoader> uclc = ucl.getClass();
無效.
另一方面,
Class<? extends URLClassLoader> uclc = ucl.getClass();
將是有效.
這篇關于為什么不能分配 I <?擴展類型>到<類型>?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!