什么类型的令牌恰好是Java 10中的“var”?

在上一期Heinz Kabutz的新闻通讯#255 Java 10:Inferred Local Variables中 ,显示var不是Java 10中的保留字,因为您也可以使用var作为标识符:

 public class Java10 { var var = 42; // <-- this works } 

但是,您不能使用ie assert作为标识符,因为var assert = 2 ,因为assert是保留字。

正如在链接时事通讯中所说的那样, var不是保留字这一事实是个好消息,因为这允许使用var作为标识符的旧版Java代码在Java 10中编译时没有问题。

那么,什么是var呢? 它既不是显式类型也不是语言的保留字,因此它被允许作为标识符,但是当它用于在Java 10中声明局部变量时它确实具有特殊含义。我们在a的上下文中究竟是什么意思局部变量声明?

此外,除了支持向后兼容性(通过允许包含var作为标识符的旧代码进行编译), var还有其他优点吗?

根据JEP-286:局部变量类型推断 , var

不是关键字; 相反,它是一个保留类型名称

(早期版本的JEP为实现保留类型名称或上下文相关关键字留下了空间;最终选择了前一个路径。)

因为它不是“保留关键字”,所以仍然可以在变量名(和包名)中使用它,但不能在类或接口名中使用它。

我认为不使用var保留关键字的最大原因是与旧源代码的向后兼容性。

var是保留类型名称var不是关键字,它是保留类型名称。

我们可以创建一个名为“var”的变量。

你可以在这里阅读更多细节。

 var var = 5; // syntactically correct // var is the name of the variable “var” as a method name is allowed. public static void var() { // syntactically correct } “var” as a package name is allowed. package var; // syntactically correct “var” cannot be used as the name of a class or interface. class var{ } // Compile Error LocalTypeInference.java:45: error: 'var' not allowed here class var{ ^ as of release 10, 'var' is a restricted local variable type and cannot be used for type declarations 1 error interface var{ } // Compile Error var author = null; // Null cannot be inferred to a type LocalTypeInference.java:47: error: cannot infer type for local variable author var author = null; ^ (variable initializer is 'null') 1 error