如何理解 java class 文字?

How to understand java class literals?

在 JLS 15.8.2 中,显示

A class literal is an expression consisting of the name of a class, interface, array, or primitive type, or the pseudo-type void, followed by a . and the token class.

而在 WIKI 中,它表示

An expression in a programming language is a combination of explicit values, constants, variables, operators, and functions...

而且我在here

中没有看到类似的运算符

我知道String.classClass<String>的一个实例,只是不明白为什么我们可以这样写一个表达式。

那么 .class 到底是什么以及如何理解这个表示法?

如果对象 foo 上有一个名为 bar 的 public 字段,您可以简单地使用 foo.bar 来寻址该字段。这里是一样的 - 将其视为隐式 public 静态字段,称为 class.

. 实际上是一个运算符:它是 "dot operator"。它没有在官方运营商列表中提及,因为……谁知道呢。

然而 the official tutorial 中提到了它:

Code that is outside the object's class must use an object reference or expression, followed by the dot (.) operator, followed by a simple field name,

语法 Foo.class(new Foo()).getClass() 的快捷方式,无需内存分配。每当方法想要接收 Class<?> 的实例作为参数时,它都非常有用。

标准库中的一些示例:

String.class 是一个 primary 表达式,它不会分解为操作数和运算符,但这并不能阻止它具有内部句法结构。我相信您会同意 " 也不是运算符,但 "i am a string" 是文字表达式。