简体   繁体   中英

What magic makes object.getClass() in Java return a typed Class instance?

In Java, Object.getClass has a type signature of public final Class<?> getClass() , but the JavaDoc comment mentions that it will really be " Class<? extends |X|> where |X| is the erasure of the static type of the expression on which getClass is called".

This is indeed the case and enforced by the compiler, supported by the IDE:s etc, but what magic make this tick? Does the compiler treat this method in a special way? Does it actually generate an override of getClass() for each type?

I understand that this is solely a compile time construct, at runtime it will not make any difference what the generic type parameter of Class is/was.

Yes, the compiler treats the method specially. For example, see calls to createGetClassMethod() in Eclipse's compiler in the Scope class. (There are a few other calls to this method in the same class.)

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