每天一分钟来一颗Java语法糖(一)语法糖介绍
Java语法糖介绍
语法糖简介
语法糖(Syntactic Sugar/SyntaxSugar),也称糖衣语法,是由英国计算机学家 Peter.J.Landin(彼得·兰丁) 发明的一个术语,指在计算机语言中添加的某种语法,这种语法对语言的功能并没有影响,但是更方便程序员使用。语法糖就是对现有语法的一个封装。简而言之,语法糖让程序更加简洁,有更高的可读性。
维基百科介绍如下
In computer science, syntactic sugar is syntax within a programminglanguage that is designed to make things easier to read or to express。
语法糖好处
- 语法糖使得程序员更容易编写程序,更清晰准确表达业务逻辑。
- 不仅仅是语法的转换,还包括一些小的改进。
解语法糖
Java虚拟机并不支持语法糖。语法糖在编译阶段就会被还原成简单的基础语法结构,这个过程就是解语法糖。
Java中的语法糖只存在于编译期,在编译器将 .java 源文件编译成 .class 字节码时(javac命令)。
例如查看自动拆箱自动装箱的字节码,图片来自自动拆箱自动装箱
实际上源码还是简单的基础语法结构
如果查看com.sun.tools.javac.main.JavaCompiler的源码,就会发现在compile()中有一个步骤就是调用desugar(),这个方法就是负责解语法糖而实现的。
以下是来自笔者$JAVA_HOME/lib/tools.jar包内的com.sun.tools.javac.main.JavaCompiler类中的源码
public void compile(List<JavaFileObject> var1, List<String> var2, Iterable<? extends Processor> var3) {
if (var3 != null && var3.iterator().hasNext()) {
this.explicitAnnotationProcessingRequested = true;
}
if (this.hasBeenUsed) {
throw new AssertionError("attempt to reuse JavaCompiler");
} else {
this.hasBeenUsed = true;
this.options.put(Option.XLINT_CUSTOM.text + "-" + LintCategory.OPTIONS.option, "true");
this.options.remove(Option.XLINT_CUSTOM.text + LintCategory.OPTIONS.option);
this.start_msec = now();
try {
this.initProcessAnnotations(var3);
this.delegateCompiler = this.processAnnotations(this.enterTrees(this.stopIfError(CompileState.PARSE, this.parseFiles(var1))), var2);
this.delegateCompiler.compile2();
this.delegateCompiler.close();
this.elapsed_msec = this.delegateCompiler.elapsed_msec;
} catch (Abort var8) {
if (this.devVerbose) {
var8.printStackTrace(System.err);
}
} finally {
if (this.procEnvImpl != null) {
this.procEnvImpl.close();
}
}
}
}
private void compile2() {
try {
label44:
switch(2.$SwitchMap$com$sun$tools$javac$main$JavaCompiler$CompilePolicy[