一、什么是语法糖?
语法糖(Syntactic Sugar)也称糖衣语法,指在计算机语言中添加的某种语法,这种语法对语言的功能并没有影响,但是更方便程序员使用。
二、Java中有哪些常见的语法糖?
Java中有以下几种常见的语法糖:
- switch支持String与枚举
- 泛型
- 自动装箱与拆箱
- 可变长参数
- 枚举
- 内部类
- 条件编译
- 断言
- 数值字面量
- for-each
- try-with-resource
- Lambda表达式
- …
1、switch支持String与枚举
背景:switch
天生就支持基本数据类型,如int
、long
等,但在Java 7之后开始支持String
switch
使用String
的代码如下:
public class SwitchDemoString {
public static void main(String[] args) {
String str = "world";
switch (str) {
case "hello":
System.out.println("hello");
break;
case "world":
System.out.println("world");
break;
default:
break;
}
}
}
反编译后内容如下:
public class SwitchDemoString {
public static void main(String[] args) {
String str = "world";
String s;
switch ((s = str).hashCode()) {
default:
break;
case 99162322:
if(s.equals("hello"))
System.out.println("hello");
break;
case 113318802:
if(s.equals("world"))
System.out.println("world");
break;
}
}
}
总结:switch
对于String
的支持其实是通过hashCode()
和equals()
方法来实现的
2、泛型
背景:在前面的文章我们知道,泛型是在编译阶段发生的,用来规范我们开发,而JVM其实是不认识这种语法的。(相关文章可参考《什么是泛型?有什么用?》)
举例如下:
Map<String, String> map = new HashMap<String, String>();
map.put("name", "gary");
map.put("sex", "male");
解语法糖后:
Map map = new HashMap();
map.put("name", "gary");
map.put("sex", "male");
总结:JVM并不能解析泛型语法,只能通过类型擦除的方式解语法糖
3、自动装箱与拆箱
什么是装箱与拆箱?:基本数据类型转换为包装类叫装箱,包装类转换为基本数据类型叫拆箱
自动装箱代码如下:
int i = 5;
Integer integer = i;
反编译后代码如下:
int i = 5;
Integer integer = Integer.valueOf(i);
自动拆箱代码如下:
Integer integer = 5;
int i = integer;
反编译后代码如下:
Integer integer = Integer.valueOf(5);
int i = integer.intValue();
总结:自动装箱是通过valueOf()
实现的,而自动拆箱是通过intValue()
实现的
// TODO