jjzjj

java - getClass() 文档中的 "the erasure of the static type of the expression on which it is called"是什么意思?

coder 2024-03-03 原文

"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<? extends List>而不是 Class<? extends List<String>> .

关于java - getClass() 文档中的 "the erasure of the static type of the expression on which it is called"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19332856/

有关java - getClass() 文档中的 "the erasure of the static type of the expression on which it is called"是什么意思?的更多相关文章

随机推荐