Return get Class 方法的类型与实际返回类型不同

Return type of get Class method is different from actual returntype

当我创建一个 class A 的实例并尝试访问它的 getClass() 方法时,它的 return 类型与 java 对象 class.

A a = new A() ;
Class<? extends A> clazz = a.getClass();

即使我在 Intellij 中访问上面提到的 getClass 方法,它也说它的 return 类型是 Class<? extends A> ,甚至 java 文档也说它是 returns通配符扩展上限。我完全可以接受。因为我可以创建 B 的实例并引用 A 并访问 getClass 方法。

但是为什么getClass方法的return类型在Object中只是Class<?>class

编辑 1(在 Andy Turner 的评论之后)

Class A {
   List<?> returningNullList() {
     return null;
   } 
} 

当我创建 A 的实例并尝试访问 returningNullList () 方法时,它没有给我 return 类型 List<? extends A>。但是当我尝试访问 getClass 方法时它说 return 类型是 Class<? extends A> 尽管实际的硬编码 return 类型是 Class<? > 在 Object.java 文件

getClass 方法是否被编译器特殊处理?

But why does the return type of the getClass method is justClass<?> in the Object class

Class<?>Class<? extends Object> 相同,因为所有 类(Object 除外)都有 Object 作为超类。没有理由明确包括该界限。

阅读文档,即class中getClass()的javadoc Object:

The actual result type is Class<? extends |X|> where |X| is the erasure of the static type of the expression on which getClass is called. For example, no cast is required in this code fragment:

Number n = 0;
Class<? extends Number> c = n.getClass();

粗体来自javadoc,不是我加的

对于classObject本身来说,意味着return类型是Class<? extends Object>,但是由于Class<?>是shorthand对于Class<? extends Object>,javadoc 只显示 shorthand.

引用 Java 语言规范,第 4.5.1. Type Arguments of Parameterized Types 节:

The wildcard ? extends Object is equivalent to the unbounded wildcard ?.