groovy api tutorial

21
Groovy API QIYI AD Team Yan Lei

Upload: guligala

Post on 10-May-2015

1.822 views

Category:

Documents


7 download

TRANSCRIPT

Groovy API

QIYI AD TeamYan Lei

You can define a variable without specifying TYPE def user = new User()

You can define function arguments without TYPE void testUser(user) { user.shout() }

Types in Groovy 1.1.getClass().name // java.math.BigDecimal

Multimethords Example

Dynamic Type

import java.util.*;public class UsingCollection{

public static void main(String[] args){

ArrayList<String> lst = new ArrayList<String>();Collection<String> col = lst;lst.add("one" );lst.add("two" );lst.add("three" );lst.remove(0);col.remove(0);System.out.println("Added three items, remove two, so 1 item to remain." );System.out.println("Number of elements is: " + lst.size());System.out.println("Number of elements is: " + col.size());

}}

Example

Please Give Result running on Java & Groovy

One of The biggest contributions of GDK is extending the JDK with methods that take closures.

Define a closure def closure = { println “hello world”}

Exampledef pickEven(n, block){

for(int i = 2; i <= n; i += 2){block(i)

}}pickEvent(10, {println it}) === pickEvent(10) {println it} when closure is the last argumentdef Total = 0; pickEvent(10) {total += it}; println total

Using Closures

When you curry( ) a closure, you’re asking the parameters to be prebound.

Exampledef tellFortunes(closure){

Date date = new Date("11/15/2007" )postFortune = closure.curry(date)postFortune "Your day is filled with ceremony"postFortune "They're features, not bugs"

}tellFortunes() { date, fortune ->

println "Fortune for ${date} is '${fortune}'"}

Curried Closure

def examine(closure){println "$closure.maximumNumberOfParameters parameter(s) given:"for(aParameter in closure.parameterTypes) { println aParameter.name }

}examine() { } // 1, Objectexamine() { it } // 1, Objectexamine() {-> } // 0examine() { val1 -> } // 1, Objectexamine() {Date val1 -> } // 1, Dateexamine() {Date val1, val2 -> } // 2, Date, Objectexamine() {Date val1, String val2 -> } // 2, Date, String

Dynamic Closures

Three properties of a closure determine which object handles a method call from within a closure. These are this, owner, and delegate. Generally, the delegate is set to owner, but changing it allows you to exploit Groovy for some really good metaprogramming capabilities.

Example ???

Closure Delegation

Creating String with ‘, “(GStringImpl), ‘’’(multiLine)

getSubString using [] , “hello”[3], “hello”[1..3]

As String in Java, String in Groovy is immutable.

Working with String

Problemprice = 568.23company = 'Google'quote = "Today $company stock closed at $price"println quotestocks = [Apple : 130.01, Microsoft : 35.95]stocks.each { key, value ->

company = keyprice = valueprintln quote

}

Why ? When you defined the GString—quote—you bound the variables company and

price to a String holding the value Google and an Integer holding that obscene stock price, respectively. You can change the company and price references all you want (both of these are referring to immutable objects) to refer to other objects, but you’re not changing what the GString instance has been bound to.

Solution Using closure quote = “Today ${->company} stock closed at ${->price}”

GString Lazy Evaluation Problem

“hello world” -= “world” for(str in ‘abc’..’abz’){ print “${str} ”} Regular Expressions

Define pattern : def pattern = ~”[aAbB]” Matching

=~ , ==~ “Groovy is good” =~ /g|Groovy/ //match “Groovy is good” ==~ /g|Groovy/ //no match ('Groovy is groovy, really groovy'=~

/groovy/).replaceAll(‘good' )

String Convenience Methods

def a = [1,2,3,4,5,6,7] // ArrayList Def b = a[2..5] // b is an object of RandomAccessSubList Using each for iterating over an list

a.each { println it } Finder Methords: find & findAll

a.find {it > 6} //7 return the first match result a.findAll {it > 5} //[5,7] return a list include all matched members

Convenience Method collect inject join flatten *

List

def a = [s:1,d:2,f:3] //LinkedHashMap fetch value by Key: a.s, a[“s”] a.each {entry -> println “$entry.key :

$entry.value” } a.each {key, value -> println “$key : $value”

} Methods

Collect, find, findAll Any, every groupBy

Map

The dump and inspect Methods dump( ) lets you take a peek into an object.

Println “hello”.dump()java.lang.String@5e918d2 value=[h, e, l, l, o] offset=0 count=5 hash=99162322

Groovy also adds another method, inspect( ), to Object. This method is intended to tell you what input would be needed to create an object. If unimplemented on a class, it simply returns what toString( ) returns. If your object takes extensive input, this method will help users of your class figure out at runtime what input they should provide.

Object Extensions

identity: The Context Methodlst = [1, 2]lst.identity {

add(3)add(4)println size() //4println contains(2) // trueprintln "this is ${this}," //this is Identity@ce56f8,println "owner is ${owner}," //owner is Identity@ce56f8,println "delegate is ${delegate}." //delegate is [1, 2, 3, 4].

}

Object Extensions

Sleep: suppresses the Interrupted-Exception. If you do care to be interrupted, you don’t have to

endure try-catch. Instead, in Groovy, you can use a variation of the previous sleep( ) method that accepts a closure to handle the interruption.

new Object().sleep(2000) {println "Interrupted... " + itflag //if false, the thread will sleep 2 second as if there is no interruption

}

Object Extensions

class Car{int miles, fuelLevelvoid run(){println “boom …”}Void status(int a, String b) {println “$a --- $b”}

}car = new Car(fuelLevel: 80, miles: 25)

Indirect Property Accessprintln car[“miles”]

Indirect Method Invokecar.invokeMethod(“status”, [1,”a”] as Object[])

Object Extensions

Overloaded operators for Character, Integer, and so on. Such as plus( ) for operator +, next( ) for operator++, and so on.

Number (which Integer and Double extend) has picked up the iterator methods upto( ) and downto( ). It also has the step( ) method.

Thread.start{} & Thread.startDaemon()

java.lang extensions

Read file println new File('thoreau.txt' ).text new File('thoreau.txt' ).eachLine { line ->println

line} println new File('thoreau.txt' ).filterLine { it =~ /life/

} Write file

new File("output.txt" ).withWriter{ file ->file << "some data..."

}

java.io Extensions

Details about calling a method

Groovy Object

Use MetaClass to modify a class at runtime Dynamic Adding or modifying Method

A.metaclass.newMethod= { println “new method”}

Dynamic Adding or modifying variable A.metaClass.newParam = 1

After these, U can new A().newMethod() println new A().newParam

MetaClass

Implements GroovyInterceptable & define method invokeMethod(String name, args)

Using MetaClass define a closure for metaclass Car.metaClass.invokeMethod = { String name,

args -> //…}

Intercepting Methods