Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

generics

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.

like image 544
SoftMemes Avatar asked Sep 17 '13 16:09

SoftMemes


1 Answers

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.)

like image 67
Brett Kail Avatar answered Oct 21 '22 15:10

Brett Kail