程序员

Groovy语法

2018-08-05  本文已影响271人  刺雒

注释

//这是单行注释
/*这是多行注释*/

// GroovyDoc注释/** */

/**
* 这是文档注释
*/

变量名

map = [:]
map."name" = "james"
map."a-b-c" = "dota"

map./slashy string/
map.$/dollar slashy string/$

def firstname = "Homer"
map."Simpson-${firstname}" = "Homer Simpson"

字符串

'hello world'
""" line 1
line 2
line 3
"2 + 3 is ${2+3}" // output 2+3 is 5
"2 + 3 is ${def i = 2; def j = 3; i+j}" // output 2 + 3 is 5

def person = [name: 'James', age: 36]
"$person.name is 36" // output James is 36
"person is $def age = 10" // 不合法
""
def person = "1 + 2 is ${->3}"

def person = "1 + 2 is ${w -> w.append("5")}"
def person = "1 + 2 is ${w -> w << "5"}"
def num = 3
def normal = "1 + 2 is ${-> num}"
def cls = "1 + 2 is ${num}"
println(normal) // output "1 + 2 is 3"
println(cls) // output "1 + 2 is 3"

num = 5
println(normal) // output "1 + 2 is 3"
println(cls) // output "1 + 2 is 5"
def key = "a"
map = [${key}:"James"]
printfln map["a"] // output null
def a = 'A'

def b = 'A' as char

def c = (char)'A'

Numbers

long i =  1223_123_1L
long i = 0x7fff_8fff_0000_ffff
Integer a = 42I或42i
Long b = 42L或42l
BigInteger c = 42G或42g
Double d = 42.2D或42.5d
Float e = 42.2F或42.1f
BigDecimal f = 42.24G或42.24g

List

def listone = [1,2,3,4]
def listtwo = [1, 1.24, "hello"]s
def list = [1,2,3,4] as LinkedList
def list = [1,2,3,4]
list[-1]
list[2]
list[1..3]

list << 5
list = [[0,1],[2,3]]
list[0][1]

Arrays

int[] list = [1,2,3,4,5]
def list = [1,2,3,4] as int[]

Maps

def colors = [red: '#FF0000', green: '#00FF00', blue: '#0000FF']

colors['pink'] = '#FF00FF'
colors.yellow = '#FFFF00'
def key = 'pink'
def map = [(key) :123]

操作符

def num = 2 ** 3
def a = 8
def b = a < 7 ?:10
// 等价于
if(a < 7) {
    b = ture
} else {
    b = 10
}
class Car {
    String make
    String model
}
def cars = [
       new Car(make: 'Peugeot', model: '508'),
       new Car(make: 'Renault', model: 'Clio')]       
def makes = cars*.make                                
assert makes == ['Peugeot', 'Renault'] 
def list = [1,2,3]
int f(int i, int j, int z) {
    return i * j + z
}

f(*list)

def other = [4,5, *list] // output [4,5,1,2,3]
def other = [4,5, list] // output [4,5,[1,2,3]]
def map = [red : 0x1]
def add = [green : 0x2, * : map]
// output [green:34, red:17]
def i = 0..5 // output [0,1,2,3,4,5]
def i = 0..<5 // output [0,1,2,3,4]
def i = 'a'..'d' // output ['a','b','c','d']
(1<=>1) = 0
(2<=>1) = 1
(2<=>3) = -1
def list = [0,1,2,3,4]
list[3] = 5 // output [0,1,2,5,4]
list[4] // output 4
def list = [1,2,3]
5 in list // output false
def list1 = [1,2,3]
def list2 = [1,2,3]
list1.is(list2) // output false
list1 == list2 // output true

Integer a = new Integer(5);
Integer b = new Integer(5);
println a.is(b) // output false
println a == b // output true
Integer x = 123 as String  // output "123"
String a = "123" as Map // 抛异常

import java.util.Date as SQLDate

SQLDate date = new SQLDate() 
println 'Hello'                                 
int power(int n) { 2**n }                       
println "2^6==${power(6)}"

// 转换之后
import org.codehaus.groovy.runtime.InvokerHelper
class Main extends Script {
    int power(int n) { 2** n}                   
    def run() {
        println 'Hello'                         
        println "2^6==${power(6)}"              
    }
    static void main(String[] args) {
        InvokerHelper.runScript(Main, args)
    }
}
int declared  = 0
undeclared  = 10
void pow() {
    println declared
    println undeclared
}

pow()
public class Study extends Script
{
  public void pow()
  {
    CallSite[] arrayOfCallSite = $getCallSiteArray();
    arrayOfCallSite[2].callCurrent(this, arrayOfCallSite[3].callGroovyObjectGetProperty(this));
    arrayOfCallSite[4].callCurrent(this, arrayOfCallSite[5].callGroovyObjectGetProperty(this));
  }
  
  public Object run()
  {
    CallSite[] arrayOfCallSite = $getCallSiteArray();
    int declared = 0;
    int i = 10;
    ScriptBytecodeAdapter.setGroovyObjectProperty(Integer.valueOf(i), Study.class, this, (String)"undeclared");
    pow();
   }
  
  public static void main(String... args)
  {
    CallSite[] arrayOfCallSite = $getCallSiteArray();
    arrayOfCallSite[0].call(InvokerHelper.class, Study.class, args);
  }
  
}

方法和类

public class Study {
    public String name;

    class School {
        Study study = new Study();
        public void driver() {
        }
    }
}
public class Study {
    public Study(String name, int age) {
        
    }
    
    public void pow(int a, int b = 9) {
    }
}


Study study = ["1",2] 
study.pow([5,6])
study.pow(5)

Traits(特征)

trait FlyingAbility {                           
    String fly() {
        println "I'm flying!" 
    }          
}

class Bird implements FlyingAbility {}          
def b = new Bird()                              
println b.fly()  
trait Greetable {
    abstract String name()                              
    String greeting() { "Hello, ${name()}!" }           
}
trait Greeter {
    private String greetingMessage() {                      
        'Hello from a private method!'
    }
    String greet() {
        def m = greetingMessage()                           
        println m
    }
}
public trait FlyingAbility {
    
    String fly() {
        return this
    }
}
trait Named {
    String name                             
}
trait Counter {
    public int num = 1
    private int count = 0                   
    int count() { count += 1; count }       
}
trait FlyingAbility {                           
        String fly() { "I'm flying!" }          
}
trait SpeakingAbility {
    String speak() { "I'm speaking!" }
}

class Duck implements FlyingAbility, SpeakingAbility {}
trait FlyingAbility {                           
        String fly() { 
            "I'm flying!" 
        }          
}
trait SpeakingAbility extends FlyingAbility {
    String fly() {
        "I can speaking!" 
    }
}

闭包

{ item++ }                                          

{ -> item++ }                                       

{ println it }                                      

{ it -> println it }                                

{ name -> println name }                            

{ String x, int y ->                                
    println "hey ${x} the value is ${y}"
}

{ reader ->                                         
    def line = reader.readLine()
    line.trim()
}
def listener = { e ->  e } 
println listener //output `groovy.lang.Closure`对象
println listener("lis") // output  "lis"

Closure callback = { println 'Done!' }     

Closure<Boolean> isTextFile = {
    File it -> it.name.endsWith('.txt')                     
}
def isOdd = { 
    int i -> i%2 != 0 
}

isOdd(2)
isOdd.call(2)

def f = {-> printfln it}
def f = {it -> println it}

闭包中的this,owner,delegate

class Enclosing {
    void run() {
        def whatIsThisObject = { getThisObject() }          
        assert whatIsThisObject() == this                   
        def whatIsThis = { this }                           
        assert whatIsThis() == this   //  等价                     
    }
}
class EnclosedInInnerClass {
    class Inner {
        Closure cl = { this }                               
    }
    void run() {
        def inner = new Inner()
        // 内部类定义闭包使用this,则指向内部类
        assert inner.cl() == inner                      
    }
}
class NestedClosures {
    void run() {
        def nestedClosures = {
            def cl = { this }                               
            cl()
        }
        // 闭包嵌套闭包,则this也指向类
        assert nestedClosures() == this                     
    }
}
上一篇 下一篇

猜你喜欢

热点阅读