• Java中的语法糖


    同步发布于个人博客:https://njlife.top/2019/07/01/Java中的语法糖/

    语法糖

    语法糖(Syntactic Sugar),也称糖衣语法,是由英国计算机学家 Peter.J.Landin 发明的一个术语,指在计算机语言中添加的某种语法,这种语法对语言的功能并没有影响,但是更方便程序员使用。简而言之,语法糖让程序更加简洁,有更高的可读性。

    语法糖的存在主要是方便开发人员使用。但其实,Java虚拟机并不支持这些语法糖。这些语法糖在编译阶段就会被还原成简单的基础语法结构,这个过程就是解语法糖

    说到编译,大家肯定都知道,Java语言中,javac命令可以将后缀名为.java的源文件编译为后缀名为.class的可以运行于Java虚拟机的字节码。如果你去看com.sun.tools.javac.main.JavaCompiler的源码,你会发现在compile()中有一个步骤就是调用desugar(),这个方法就是负责解语法糖的实现的。

    语法糖本质

    糖一:泛型

    很多语言都是支持泛型的,但是很多人不知道的是,不同的编译器对于泛型的处理方式是不同的,通常情况下,一个编译器处理泛型有两种方式:Code specializationCode sharing。C++和C#是使用Code specialization的处理机制,而Java使用的是Code sharing的机制。

    Code sharing方式为每个泛型类型创建唯一的字节码表示,并且将该泛型类型的实例都映射到这个唯一的字节码表示上。将多种泛型类形实例映射到唯一的字节码表示是通过类型擦除(type erasue)实现的。

    也就是说,对于Java虚拟机来说,他根本不认识Map<String, String> map这样的语法。需要在编译阶段通过类型擦除的方式进行解语法糖。

    类型擦除的主要过程如下:

    1. 将所有的泛型参数用其最左边界(最顶级的父类型)类型替换。
    2. 移除所有的类型参数。

    这段代码

    Map<String, String> map = new HashMap<String, String>();  
    map.put("name", "zhangsan");  
    map.put("age", "15");
    

    解语法糖之后会变成

    Map map = new HashMap();  
    map.put("name", "zhangsan");  
    map.put("age", "15"); 
    

    这段代码

    public static <A extends Comparable<A>> A max(Collection<A> xs) {
        Iterator<A> xi = xs.iterator();
        A w = xi.next();
        while (xi.hasNext()) {
            A x = xi.next();
            if (w.compareTo(x) < 0)
                w = x;
        }
        return w;
    } 
    

    解语法糖之后会变成

    public static Comparable max(Collection xs){
        Iterator xi = xs.iterator();
        Comparable w = (Comparable)xi.next();
        while(xi.hasNext())
        {
            Comparable x = (Comparable)xi.next();
            if(w.compareTo(x) < 0)
                w = x;
        }
        return w;
    }  
    

    所以,虚拟机中没有泛型,只有普通类和普通方法,所有泛型类的类型参数在编译时都会被擦除,泛型类并没有自己独有的Class类对象。比如并不存在List<String>.class或是List<Integer>.class,而只有List.class

    糖二:自动装箱与解箱

    自动装箱就是Java自动将原始类型值转换成对应的对象,比如将int的变量转换成Integer对象,这个过程叫做装箱,反之将Integer对象转换成int类型值,这个过程叫做拆箱。因为这里的装箱和拆箱是自动进行的非人为转换,所以就称作为自动装箱和拆箱。原始类型byte, short, char, int, long, float, double 和 boolean 对应的封装类为Byte, Short, Character, Integer, Long, Float, Double, Boolean。

    自动装箱

    public static void main(String[] args) {
        int i = 10;
        Integer n = i;
    }
    

    反编译之后

    public static void main(String args[]){
        int i = 10;
        Integer n = Integer.valueOf(i);
    }
    

    自动拆箱

    public static void main(String[] args) {
        Integer i = 10;
        int n = i;
    }
    

    反编译之后

    public static void main(String args[]){
        Integer i = Integer.valueOf(10);
        int n = i.intValue();
    }
    

    从反编译得到内容可以看出,在装箱的时候自动调用的是Integer的valueOf(int)方法。而在拆箱的时候自动调用的是Integer的intValue()方法。

    所以,装箱过程是通过调用包装器的valueOf(...)方法实现的,而拆箱过程是通过调用包装器的xxxValue()方法实现的。

    糖三:枚举

    Java SE5提供了一种新的类型-Java的枚举类型,关键字enum可以将一组具名的值的有限集合创建为一种新的类型,而这些具名的值可以作为常规的程序组件使用,这是一种非常有用的功能。

    要想看源码,首先得有一个类吧,那么枚举类型到底是什么类呢?是enum吗?答案很明显不是,enum就和class一样,只是一个关键字,他并不是一个类,那么枚举是由什么类维护的呢,我们简单的写一个枚举:

    public enum t {
        SPRING,SUMMER;
    }
    

    反编译之后

    public final class T extends Enum
    {
        private T(String s, int i)
        {
            super(s, i);
        }
        public static T[] values()
        {
            T at[];
            int i;
            T at1[];
            System.arraycopy(at = ENUM$VALUES, 0, at1 = new T[i = at.length], 0, i);
            return at1;
        }
    
        public static T valueOf(String s)
        {
            return (T)Enum.valueOf(demo/T, s);
        }
    
        public static final T SPRING;
        public static final T SUMMER;
        private static final T ENUM$VALUES[];
        static
        {
            SPRING = new T("SPRING", 0);
            SUMMER = new T("SUMMER", 1);
            ENUM$VALUES = (new T[] {
                SPRING, SUMMER
            });
        }
    }
    

    通过反编译后代码我们可以看到,public final class T extends Enum,说明,该类是继承了Enum类的,同时final关键字告诉我们,这个类也是不能被继承的。当我们使用enmu来定义一个枚举类型的时候,编译器会自动帮我们创建一个final类型的类继承Enum类,所以枚举类型不能被继承。

    糖四:内部类

    内部类又称为嵌套类,可以把内部类理解为外部类的一个普通成员。

    内部类之所以也是语法糖,是因为它仅仅是一个编译时的概念,outer.java里面定义了一个内部类inner,一旦编译成功,就会生成两个完全不同的.class文件了,分别是outer.classouter$inner.class。所以内部类的名字完全可以和它的外部类名字相同。

    public class OutterClass {
        private String userName;
    
        public String getUserName() {
            return userName;
        }
    
        public void setUserName(String userName) {
            this.userName = userName;
        }
    
        public static void main(String[] args) {
    
        }
    
        class InnerClass{
            private String name;
    
            public String getName() {
                return name;
            }
    
            public void setName(String name) {
                this.name = name;
            }
        }
    }
    

    以上代码编译后会生成两个class文件:OutterClass$InnerClass.classOutterClass.class 。当我们尝试对OutterClass.class文件进行反编译的时候,命令行会打印以下内容:

    Parsing OutterClass.class...Parsing inner class OutterClass$InnerClass.class... Generating OutterClass.jad

    他会把两个文件全部进行反编译,然后一起生成一个OutterClass.jad文件。文件内容如下:

    public class OutterClass
    {
        class InnerClass
        {
            public String getName()
            {
                return name;
            }
            public void setName(String name)
            {
                this.name = name;
            }
            private String name;
            final OutterClass this$0;
    
            InnerClass()
            {
                this.this$0 = OutterClass.this;
                super();
            }
        }
    
        public OutterClass()
        {
        }
        public String getUserName()
        {
            return userName;
        }
        public void setUserName(String userName){
            this.userName = userName;
        }
        public static void main(String args1[])
        {
        }
        private String userName;
    }
    

    糖五:switch支持String

    从Java 7 开始,Java语言中的语法糖在逐渐丰富,其中一个比较重要的就是Java 7中switch开始支持String。

    在开始coding之前先科普下,Java中的swith自身原本就支持基本类型。比如int、char等。对于int类型,直接进行数值的比较。对于char类型则是比较其ascii码。所以,对于编译器来说,switch中其实只能使用整型,任何类型的比较都要转换成整型。比如byte。short,char(ackii码是整型)以及int。

    那么接下来看下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 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是通过equals()hashCode()方法来实现的。hashCode()方法返回的是int。

    仔细看下可以发现,进行switch的实际是哈希值,然后通过使用equals方法比较进行安全检查,这个检查是必要的,因为哈希可能会发生碰撞。因此它的性能是不如使用枚举进行switch或者使用纯整数常量,但这也不是很差。

    糖六:方法变长参数

    可变参数(variable arguments)是在Java 1.5中引入的一个特性。它允许一个方法把任意数量的值作为参数。

    public static void main(String[] args){
        print("111", "222", "333", "444");
    }
    
    public static void print(String... strs){
        for (int i = 0; i < strs.length; i++){
            System.out.println(strs[i]);
        }
    }
    

    反编译之后

    public static void main(String args[])
    {
        print(new String[] {
            "111", "222", "333", "444"
        });
    }
    
    public static transient void print(String strs[])
    {
        for(int i = 0; i < strs.length; i++)
            System.out.println(strs[i]);
    
    }
    

    从反编译后代码可以看出,可变参数在被使用的时候,他首先会创建一个数组,数组的长度就是调用该方法是传递的实参的个数,然后再把参数值全部放到这个数组当中,然后再把这个数组作为参数传递到被调用的方法中。

    糖七:for-each

    增强for循环(for-each)相信大家都不陌生,日常开发经常会用到的,他会比for循环要少写很多代码,那么这个语法糖背后是如何实现的呢?

    public static void main(String... args) {
        String[] strs = {"111", "222", "333"};
        for (String s : strs) {
            System.out.println(s);
        }
    }
    

    反编译之后

    public static transient void main(String args[])
    {
        String strs[] = {
            "111", "222", "333"
        };
        String args1[] = strs;
        int i = args1.length;
        for(int j = 0; j < i; j++)
        {
            String s = args1[j];
            System.out.println(s);
        }
    
    }
    

    糖八:try-with-resource

    Java里,对于文件操作IO流、数据库连接等开销非常昂贵的资源,用完之后必须及时通过close方法将其关闭,否则资源会一直处于打开状态,可能会导致内存泄露等问题。

    关闭资源的常用方式就是在finally块里是释放,即调用close()方法。比如,我们经常会写这样的代码:

    public static void main(String[] args) {
        BufferedReader br = null;
        try {
            String line;
            br = new BufferedReader(new FileReader("xxx.txt"));
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            // handle exception
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException ex) {
                // handle exception
            }
        }
    }
    

    从Java 7开始,jdk提供了一种更好的方式关闭资源,使用try-with-resources>/code>语句,改写一下上面的代码,效果如下

    public static void main(String... args) {
        try (BufferedReader br = new BufferedReader(new FileReader("xxx.txt"))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            // handle exception
        }
    }
    
    public static transient void main(String args[])
        {
            BufferedReader br;
            Throwable throwable;
            br = new BufferedReader(new FileReader("xxx.txt"));
            throwable = null;
            String line;
            try
            {
                while((line = br.readLine()) != null)
                    System.out.println(line);
            }
            catch(Throwable throwable2)
            {
                throwable = throwable2;
                throw throwable2;
            }
            if(br != null)
                if(throwable != null)
                    try
                    {
                        br.close();
                    }
                    catch(Throwable throwable1)
                    {
                        throwable.addSuppressed(throwable1);
                    }
                else
                    br.close();
                break MISSING_BLOCK_LABEL_113;
                Exception exception;
                exception;
                if(br != null)
                    if(throwable != null)
                        try
                        {
                            br.close();
                        }
                        catch(Throwable throwable3)
                          {
                            throwable.addSuppressed(throwable3);
                        }
                    else
                        br.close();
            throw exception;
            IOException ioexception;
            ioexception;
        }
    }
    

    背后的原理也很简单,那些我们没有做的关闭资源的操作,编译器都帮我们做了。再次印证了语法糖的作用就是方便程序员的使用,但最终还是要转成编译器认识的语言。

    糖九:断言

    在Java中,assert关键字是从JAVA SE 1.4 引入的,为了避免和老版本的Java代码中使用了assert关键字导致错误,Java在执行的时候默认是不启动断言检查的(这个时候,所有的断言语句都将忽略!),如果要开启断言检查,则需要用开关-enableassertions-ea来开启。

    看一段包含断言的代码:

    public class AssertTest {
        public static void main(String args[]) {
            int a = 1;
            int b = 1;
            assert a == b;
            System.out.println("公众号:Hollis");
            assert a != b : "Hollis";
            System.out.println("博客:www.hollischuang.com");
        }
    }
    

    反编译后

    public class AssertTest {
       public AssertTest()
        {
        }
        public static void main(String args[])
    {
        int a = 1;
        int b = 1;
        if(!$assertionsDisabled && a != b)
            throw new AssertionError();
        System.out.println("u516Cu4F17u53F7uFF1AHollis");
        if(!$assertionsDisabled && a == b)
        {
            throw new AssertionError("Hollis");
        } else
        {
            System.out.println("u535Au5BA2uFF1Awww.hollischuang.com");
            return;
        }
    }
    
    static final boolean $assertionsDisabled = !com/hollis/suguar/AssertTest.desiredAssertionStatus();
    
    
    }
    

    糖十:数值字面量

    在java 7中,数值字面量,不管是整数还是浮点数,都允许在数字之间插入任意多个下划线。这些下划线不会对字面量的数值产生影响,目的就是方便阅读。

    比如:

    public class Test {
        public static void main(String... args) {
            int i = 10_000;
            System.out.println(i);
        }
    }
    

    反编译后

    public class Test
    {
      public static void main(String[] args)
      {
        int i = 10000;
        System.out.println(i);
      }
    }
    

    反编译后就是把_删除了。也就是说 编译器并不认识在数字字面量中的_,需要在编译阶段把他去掉。

    特别注明:文章内容整理自https://yq.aliyun.com/articles/702384

  • 相关阅读:
    IE6下实现Width:auto
    Dynamic Linq 的Like扩展
    用一句JQuery代码实现表格的简单筛选
    jquery:利用jsonp跨域访问转载
    LINQ动态组合查询
    Windows服务中Timer组件
    正则表达式笔记转载
    继LINQ动态组合查询PredicateExtensions讲解
    错误笔记:在OleDb执行下Access ,程序不报错,但是Update也更新不成功的
    jQuery 1.4 版本的十五个新特性转载
  • 原文地址:https://www.cnblogs.com/nickhan/p/11123925.html
Copyright © 2020-2023  润新知