简体   繁体   中英

Why does getClass return a Class<? extends |X|>?

I tried to understand what is the reason for getClass method to return Class<? extends |X|> Class<? extends |X|> ?

From the openjdk near public final native Class<?> getClass(); :

The actual result type is Class<? extends |X|> Class<? extends |X|> where |X| is the erasure of the static type of the expression on which getClass is called.

Why can't getClass have the same type such as XClass.class , for example:

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!
Foo foo = new SubFoo();

What do you expect foo.getClass() to return? (It's going to return SubFoo.class .)

That's part of the whole point: that getClass() returns the class of the real object, not the reference type. Otherwise, you could just write the reference type, and foo.getClass() would never be any different from Foo.class , so you'd just write the second one anyway.

(Note, by the way, that getClass() actually has its own special treatment in the type system, not like any other method, because SubFoo.getClass() does not return a subtype of Foo.getClass() .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM