zoukankan      html  css  js  c++  java
  • Groovy学习笔记(二)

      在上一篇文章中我们主要学习了如何搭建Groovy开发环境,为我们的Groovy之旅做好了准备工作,不知道你是否准备好了?接下来我们就一起看看Groovy与我们熟悉的Java有什么异同。

      Groovy是轻量级的Java,它与Java的区别主要有六点,接下来我们一一讲解。

      一:return语句和分号都是可选的。

    //Groovy Code
    def int add(a, b) {
        a + b
    }
    println add(1, 2)
    

      控制台输出:

      3

      二:方法和类默认是public的。

      三:?.操作符只有对象引用不为空时才会分派调用。

    //Groovy Code
    def foo(str) {
        str?.reverse()
    }
    println foo('evil')
    println foo(null)
    

      控制台输出:

      live

      null

      四:可以使用具名参数初始化JavaBean。

    package com.test.bean
    
    /**
     * JavaBean
     */
    class Robot {
    
        def weight, height, width
    
        def access(weight, height, width) {
            println "weight : $weight , height : $height , width : $width"
        }
    }
    

      下面是测试类:

    package com.test
    
    import com.test.bean.Robot
    
    
    /**
     * Groovy Test
     */
    class GroovyTest {
    
        public static void main(String[] args) {
            Robot robot = new Robot(weight: 30, height: 'height',  10)
            robot.access(100, robot.height, 300);
        }
    }
    

      控制台输出:

      weight : 100 , height : height , width : 300

      五:Groovy不强迫我们捕获自己不关心的异常,异常可以传递给调用者去处理。

    class ExceptionTest {
    
        def static openFile(fileName) {
            //可以不关心下面这句代码抛出的异常,交给调用者处理
            new FileInputStream(fileName)
        }
    }
    

      下面是测试类:

    class GroovyTest {
    
        public static void main(String[] args) {
            //调用者处理异常
            try {
                ExceptionTest.openFile("test.txt")
            } catch (FileNotFoundException e) {
                println e
            }
    
        }
    }
    

      控制台输出:

      java.io.FileNotFoundException: test.txt (系统找不到指定的文件。)

      六:静态方法内可以使用this来引用Class对象。

      

  • 相关阅读:
    Block & 代理
    堆&栈, 内存分配
    ASI 的 使用
    iOS开发-清理缓存功能的实现
    iOS8是如何跳转系统设置页面
    键盘弹出获取高度
    http://www.jianshu.com/collection/9a22b04a9357
    IOS 字符串中去除特殊符号 stringByTrimmingCharactersInSet
    iOS 判断输入是否全是空格
    iOS AFN 请求封装方法
  • 原文地址:https://www.cnblogs.com/yili-2013/p/4438844.html
Copyright © 2011-2022 走看看