java – 在getClass()文档中,“被调用的表达式的静态类型的擦除”是什么意思?

Object的 “public final Class<?> getClass()”方法的文档说:

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:

我不明白解释,特别是关于什么| X |被认为是 – “删除getClass被调用的表达式的静态类型”.

| X |表示什么形式?或者也许,其他地方| X |使用类型符号?

解决方法

Java语言规范 mandates这种方法由编译器以特殊的方式处理:

The method getClass returns the Class object that represents the class of the object.

A Class object exists for each reference type. It can be used,for example,to discover the fully qualified name of a class,its members,its immediate superclass,and any interfaces that it implements.

The type of a method invocation expression of getClass is Class<? extends |T|> where T is the class or interface searched (§15.12.1) for getClass.

因此,getClass的返回类型是调用getClass()的表达式的静态(编译时)类型.例如:

String s = "";
Object o = s;
Class<? extends String> sc = s.getClass(); // ok
Class<? extends Object> oc = o.getClass(); // ok
oc = sc; // ok
sc = o.getClass(); // not ok
sc = oc; // not ok

符号| X |是defined的规格如下:

Type erasure is a mapping from types (possibly including parameterized types and type variables) to types (that are never parameterized types or type variables). We write |T| for the erasure of type T. The erasure mapping is defined as follows:

  • The erasure of a parameterized type (§4.5) G<T1,...,Tn> is |G|.

  • The erasure of a nested type T.C is |T|.C.

  • The erasure of an array type T[] is |T|[].

  • The erasure of a type variable (§4.4) is the erasure of its leftmost bound.

  • The erasure of every other type is the type itself.

例如,如果我们有:

List<String> list = ...;

表达式list.getClass()的类型为<?扩展列表>而不是Class扩展List< String>>.

相关文章

ArrayList简介:ArrayList 的底层是数组队列,相当于动态数组。与 Java 中的数组相比,它的容量能动态增...
一、进程与线程 进程:是代码在数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位。 线程...
本文为博客园作者所写:&#160;一寸HUI,个人博客地址:https://www.cnblogs.com/zsql/ 简单的一个类...
#############java面向对象详解#############1、面向对象基本概念2、类与对象3、类和对象的定义格式4、...
一、什么是异常? 异常就是有异于常态,和正常情况不一样,有错误出错。在java中,阻止当前方法或作用域...
Collection接口 Collection接口 Collection接口 Collection是最基本的集合接口,一个Collection代表一组...