简体   繁体   English

什么魔术使Java中的object.getClass()返回一个类型化的Class实例?

[英]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". 在Java中, Object.getClass具有public final Class<?> getClass()的类型签名,但是JavaDoc注释提到它实际上是“ Class<? extends |X|>其中| X |是静态的擦除” getClass被称为的表达式的类型“。

This is indeed the case and enforced by the compiler, supported by the IDE:s etc, but what magic make this tick? 这确实是这种情况并由IDE支持的编译器执行:s等,但是有什么神奇之处呢? Does the compiler treat this method in a special way? 编译器是否以特殊方式处理此方法? Does it actually generate an override of getClass() for each type? 它是否实际为每种类型生成了getClass()的覆盖?

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. 我知道这只是一个编译时构造,在运行时它不会对Class的泛型类型参数有什么影响。

Yes, the compiler treats the method specially. 是的,编译器会特别处理该方法。 For example, see calls to createGetClassMethod() in Eclipse's compiler in the Scope class. 例如,请参阅Scope类中Eclipse编译器中对createGetClassMethod()调用。 (There are a few other calls to this method in the same class.) (在同一个类中还有一些其他调用此方法。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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