• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
IndustriousCoder
顽强的毅力+理智的行动+良好的心态=成功
博客园    首页    新随笔    联系   管理    订阅  订阅

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', width: 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对象。

  

 

posted @ 2015-05-03 08:22  IndustriousCoder  阅读(253)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3