groovy学习笔记

groovy学习

http://www.groovy-lang.org/documentation.html

安装:

1.1,安装gvmtools

地址:http://gvmtool.net
执行(for linux,mac,cygwin):

$ curl -s get.gvmtool.net | bash
$ source "$HOME/.gvm/bin/gvm-init.sh"
$ gvm install groovy
$ groovy -version

1.2 使用二进制包

1,下载

2,设置 GROOVY_HOME

3,将 GROOVY_HOME/bin 添加到 PATH

4,设置 JAVA_HOME

5,验证 groovy -version

使用

命令行:

groovysh

armytekiMacBook-Air:~ army$ groovysh
Groovy Shell (2.4.4, JVM: 1.7.0_45)
Type ':help' or ':h' for help.
-------------------------------------------------------------------------------
groovy:000> :h
For information about Groovy, visit:
http://groovy-lang.org 

groovy:000> class Server {String name}
===> true
groovy:000> server = new Server(name:'tt')
===> Server@3fbbaaad
groovy:000> println server.getName()
tt

界面:

groovyConsole

脚本:

groovy SomeScript

shell 脚本方式:

#!/usr/bin/env groovy

println 'Hello'
map=[:]
map."a"="1"
println map

class Person{
    String name
    Person(name){
        this.name = name
    }
}
def person = new Person(null);

println person?.name

与Java比较

http://www.groovy-lang.org/differences.html

  • 1,groovy默认引入了下列包,不需要显式import:

    java.io.*
    java.lang.*
    java.math.BigDecimal
    java.math.BigInteger
    java.net.*
    java.util.*
    groovy.lang.*
    groovy.util.*

  • 2,方法重载

Groovy的方法在运行时根据实际传入的参数类型调用,在Java中方法在编译时基于声明的类型确定。

int method(String arg) {
    return 1;
}
int method(Object arg) {
    return 2;
}
Object o = "Object";
int result = method(o);

In Java, you would have:

assertEquals(2, result);

Whereas in Groovy:

assertEquals(1, result);
  • 3,数据结构

    在Groovy中,{}是个保留字,所以用 [] 来表示数组( Java中使用{}, int[] array={1,2,3} ):

    def list = [1, 4, 6, 9]
    
    // equivalent to add()
    list << 5
    
    // call contains()
    assert 4 in list
    
    // subscript notation
    assert list[1] == 4
    

    map的key如果是字符串,不需要加引号,如果key是个变量或者对象,则like [(variableStateAcronym): stateName]

    def map = [CA: 'California', MI: 'Michigan']
    
    // add a new key value pair
    map << [WA: 'Washington']
    
    // subscript notation
    assert map['CA'] == 'California'
    
    // property notation
    assert map.WA == 'Washington'
    
  • 4,String类型

Groovy支持”,”“两种格式的字符串类型,”” 支持 “${}” 插入表达式(称为 GString):

assert 'c'.getClass()==String
assert "c".getClass()==String
assert "c${1}".getClass() in GString

对char类型,单个String字符可以赋给char类型,多个字符通过as char/asType(char) 转为char类型会取第一个字符。

// for single char strings, both are the same
assert ((char) "c").class==Character
assert ("c" as char).class==Character

// for multi char strings they are not
try {
  ((char) 'cx') == 'c'
  assert false: 'will fail - not castable'
} catch(GroovyCastException e) {
}
assert ('cx' as char) == 'c'
assert 'cx'.asType(char) == 'c'

对String换行的情况,可以用 + , \, """

throw new PluginException("Failed to execute command list-applications:" +
" The group with name " +
parameterMap.groupname[0] +
" is not compatible group of type " +
SERVER_TYPE_NAME)

throw new PluginException("Failed to execute command list-applications: \
The group with name ${parameterMap.groupname[0]} \
is not compatible group of type ${SERVER_TYPE_NAME}")

throw new PluginException("""Failed to execute command list-applications:
The group with name ${parameterMap.groupname[0]}
is not compatible group of type ${SERVER_TYPE_NAME)}""")

正则表达式,用 ~pattern 来表示,=~(创建一个Matcher), ==~ (返回boolean,字符串是否匹配pattern)

def pattern = ~/fo*/   

// matches() strings against patterns
assert 'foo' =~ pattern


assert 'foo' ==~ pattern
  • 5,基本类型和==

Groovy使用Object概念。所有的基本类型也都封装成对象。
在java中,==表示基本类型相等,对象类型相同。
在Groovy中,==表示 a.compareTo(b)==0 or a.equals(b). 相同的比较,使用a.is(b)

  • 6,Groovy 中 ; 可选

  • 7,Groovy 中 return 可选

    String toString() { return "a server" }
    String toString() { "a server" }
    
  • 8,Groovy 中 def 表示变量类型为 object

    def foo(n) {
        "Roshan"
    }
    assert foo(1) == "Roshan"
    
  • 9, Groovy 类的变量和方法默认为 public

    Groovy 默认类和方法都是是 public, 如果不是public,可以增加注解 @PackageScope

    class Person {
        String name
    }
    

    Groovy编译器生成了一个私有的属性,和对应的 setter、getter方法。

  • 10, Groovy 中可以省略 ()

    println "Hello"   ___\     println("Hello") 
    method a, b          /     method(a, b)
    
  • 11,with() 用于对同一个bean的重复操作

    server.name = xxx                       server.with {
    server.status = xxx             ___\      name = xxx ...
    ...                                /      start()
    server.start()                          }   
    
  • 12,switch

    def x = 1.23
    def result = ""
    switch (x) {
        case "foo": result = "found foo"
        // lets fall through
        case "bar": result += "bar"
        case [4, 5, 6, 'inList']:
            result = "list"
            break
        case 12..30:
            result = "range"
            break
        case Integer:
            result = "integer"
            break
        case Number:
            result = "number"
            break
        case { it > 3 }:
            result = "number > 3"
            break
        default: result = "default"
    }
    assert result == "number"
    
  • 13 import 别名

    import java.util.List as juList
    
    import static pkg.SomeClass.foo
    foo()
    
  • 14 Groovy的布尔值

    在Groovy中,所有的对象都可以强制转化成布尔值,null,void,0,空都等于false,否则是true。甚至,可以在类中增加 asBoolean() 来定制Groovy的Turth。

    if (name != null && name.length > 0) {}
    if (name) {}
    
  • 15 Groovy的安全性

    println order?.customer?.address
    

    在对象后面增加?, 可以避免抛出 NonePointerException ,并且返回 null

  • 16 异常捕获

    try {
        // ...
    } catch (any) {
        // something bad happens
    }
    

程序结构

  • 1,Groovy 脚本会编译成类,其中的执行代码放到run函数中。 脚本的名字会编译成类名,Main.groovy 变成 Main.class

    class Main {                                    
        static void main(String... args) {          
            println 'Groovy world!'                 
        }
    }
    

等于

    import org.codehaus.groovy.runtime.InvokerHelper
    class Main extends Script {                     
        def run() {
            println 'Groovy world!'
        }
        static void main(String[] args) {           
            InvokerHelper.runScript(Main, args)     
        }
    }
  • 2,闭包 { [closureParameters -> ] statements }

    Closure callback = { println "done" }
    callback()
    callback.call()
    
    def closureWithTwoArgs = { a,b -> a+b }
    assert closureWithTwoArgs(1,2) == 3
    
    def closureWithTwoArgAndDefaultValue = { int a, int b=2 -> a+b }
    assert closureWithTwoArgAndDefaultValue(1) == 3
    assert closureWithTwoArgAndDefaultValue(1,4) == 5
    

当闭包没有使用->显式定义参数,则默认用 it 表示参数。

def greeting = { "Hello, $it!" }
assert greeting('Patrick') == 'Hello, Patrick!'

入参是变长的参数列表时,可以使用 … args

def concat1 = { String... args -> args.join('') }           
assert concat1('abc','def') == 'abcdef' 
  • 3,代理
    class Enclosing {
        void run() {
            def whatIsThisObject = { getThisObject() }          
            assert whatIsThisObject() == this                   
            def whatIsThis = { this }                           
            assert whatIsThis() == this                         
        }
    }
    class Enclosing {
        void run() {
            def whatIsOwnerMethod = { getOwner() }               
            assert whatIsOwnerMethod() == this                   
            def whatIsOwner = { owner }                          
            assert whatIsOwner() == this                         
        }
    }

    class Person { String name }
    class Thing { String name }
    def p = new Person(name: 'Norman')
    def t = new Thing(name: 'Teapot')

    def upperCasedName = { delegate.name.toUpperCase() }
    upperCasedName.delegate = p
    assert upperCasedName() == 'NORMAN'
    upperCasedName.delegate = t
    assert upperCasedName() == 'TEAPOT'

你可能感兴趣的:(groovy)