2016-06-13 82 views
2

我試着明白getClass方法返回的原因是什麼Class<? extends |X|>爲什麼getClass返回一個Class <?擴展| X |>?

openjdk鄰近public final native Class<?> getClass();

實際結果類型是Class<? extends |X|> 其中|X|是靜態類型的 表達在其上getClass被稱爲的擦除。

爲什麼不能getClass有相同的類型,如XClass.class,例如:

class Foo {} 
Foo fooInstance = new Foo(); 
Class<Foo> fc = Foo.class; // Works! 
Class<Foo> fc2 = fooInstance.getClass(); // Type mismatch ;(
Class<?> fc3 = fooInstance.getClass(); // Works! 
Class<? extends Foo> fc4 = fooInstance.getClass(); // Works! 
+0

相關:HTTP:// stackoverflow.com/questions/19332856/what-is-meant-by-the-erasure-of-the-static-type-of-the-expression-on-which-it-i和http://stackoverflow.com/問題/ 18144556/java-getclass-bound-type – Tunaki

回答

5
Foo foo = new SubFoo(); 

你期望foo.getClass()返回? (它將返回SubFoo.class。)

這是整個問題的一部分:getClass()返回實際對象的類,而不是引用類型。否則,你可以只寫參考類型,並且foo.getClass()Foo.class永遠不會有任何區別,所以你只需編寫第二個參考類型。

(注意,順便說一句,這實際上getClass()在類型系統自身的特殊處理,而不是像任何其他方法,因爲SubFoo.getClass()不返回的Foo.getClass()亞型)

+0

Louis,謝謝你,我想我終於明白了。 –

相關問題