SoftMemes
SoftMemes

Reputation: 5702

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.

Upvotes: 16

Views: 640

Answers (1)

Brett Kail
Brett Kail

Reputation: 33936

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

Upvotes: 10

Related Questions