반응형

1. Common Chains

show = { println it }
square_root = { Math.sqrt(it) }

def please(_show) {
    [the: { _square_root ->
        [of: { value -> _show(_square_root(value)) }]
    }]
}

// equivalent to: please(show).the(square_root).of(100)
please show the square_root of 100

3. Script base classes

3.1. The Script class

abstract class MyBaseClass extends Script {
    String name
    void greet() { println "Hello, $name!" }
}
import org.codehaus.groovy.control.CompilerConfiguration

def config = new CompilerConfiguration()

config.scriptBaseClass = 'MyBaseClass'

def shell = new GroovyShell(this.class.classLoader, config)

shell.evaluate """
    setName 'Judith'
    greet()
"""

3.2. The @BaseScript annotation

abstract class MyBaseClass extends Script {
    String name
    void greet() { println "Hello, $name!" }
}
import groovy.transform.BaseScript

@BaseScript MyBaseClass baseScript
setName 'Judith'
greet()
@BaseScript(MyBaseClass)
import groovy.transform.BaseScript

setName 'Judith'
greet()

3.3. Alternate abstract method

def shell = new GroovyShell()
def result = shell.evaluate """
    println 'Ok'
    return 1
"""

assert result == 1
def script = shell.parse("println 'Ok'; return 1")

assert script.run() == 1

4. Adding properties to numbers

import groovy.time.TimeCategory

use(TimeCategory)  {
    println 1.minute.from.now
    println 10.hours.ago
    println new Date() - 3.months
}

5. @DelegatesTo

5.1. Explaining delegation strategy at compile time

class BodySpec {
    void p(String p) { println "p: $p"}
}
class EmailSpec {
    void from(String from) { println "From: $from"}
    void to(String... to) { println "To: $to"}
    void subject(String subject) { println "Subject: $subject"}
    void body(Closure body) {
        def bodySpec = new BodySpec()
        def code = body.rehydrate(bodySpec, this, this)
        code.resolveStrategy = Closure.DELEGATE_ONLY
        code()
    }
}
def email(Closure cl) {
    def email = new EmailSpec()
    def code = cl.rehydrate(email, this, this)
    code.resolveStrategy = Closure.DELEGATE_ONLY
    code()
}

email {
    from 'dsl-guru@mycompany.com'
    to 'john.doe@waitaminute.com', 'john@example.com'
    subject 'The pope has resigned!'
    body {
        p 'Really, the pope has resigned!'
    }
}

5.3.3. Delegate to parameter

class Email {
    String from
    String to

    void from(String from) { this.from = from }
    void to(String to) { this.to = to }
    void send(String message) {
        println "From: ${from}"
        println "To: ${to}"
        println "Message: ${message}"
    }
}
def exec(Object object, Closure closure) {
    def newClosure = closure.rehydrate(object, this, this)
    newClosure()
}

exec(new Email()) {
    from "John"
    to "Tom"
    send("Hello World")
}

8. Builders

8.2.7. JsonBuilder

import groovy.json.JsonBuilder
import groovy.json.JsonGenerator
import groovy.json.JsonOutput

def generator = new JsonGenerator.Options()
    .excludeNulls()
    .excludeFieldsByName('make', 'country')
    .excludeFieldsByType(Number)
    .addConverter(URL) { url -> "http://groovy-lang.org" }
    .build()

JsonBuilder builder = new JsonBuilder(generator)
builder.records {
    car {
        name 'HSV Maloo'
        make 'Holden'
        year 2006
        country 'Australia'
        homepage new URL('http://example.org')
        record {
            type 'speed'
            description 'production pickup truck with speed of 271kph'
        }
    }
}

String json = JsonOutput.prettyPrint(builder.toString())

println json

8.2.12. ObjectGraphBuilder

package com.acme

class Address {
    String line1
    String line2
    int zip
    String state
}
package com.acme

class Company {
    String name
    Address address
    List employees = []
}
package com.acme

class Employee {
    String name
    int employeeId
    Address address
    Company company
}
import com.acme.Address
import com.acme.Company
import com.acme.Employee

def builder = new ObjectGraphBuilder()
builder.classLoader = this.class.classLoader
builder.classNameResolver = "com.acme"

def acme = builder.company(name: 'ACME') {
    3.times {
        employee(id: it.toString(), name: "Drone $it") {
            address(line1:"Post street")
        }
    }
}

assert acme != null
assert acme instanceof Company
assert acme.name == 'ACME'
assert acme.employees.size() == 3
def employee = acme.employees[0]
assert employee instanceof Employee
assert employee.name == 'Drone 0'
assert employee.address instanceof Address

참고

반응형

'Development > Groovy' 카테고리의 다른 글

[Groovy] 자바에서 groovy script 실행  (0) 2020.12.28
[Groovy] DSL 예시  (0) 2020.12.28
[Groovy] 기본 문법  (0) 2020.12.28
[Groovy] 설치  (0) 2020.12.28

+ Recent posts