Top Banner
Groovy API QIYI AD Team Yan Lei
21
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Groovy Api  Tutorial

Groovy API

QIYI AD TeamYan Lei

Page 2: Groovy Api  Tutorial

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

Page 3: Groovy Api  Tutorial

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

Page 4: Groovy Api  Tutorial

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

Page 5: Groovy Api  Tutorial

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

Page 6: Groovy Api  Tutorial

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

Page 7: Groovy Api  Tutorial

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

Page 8: Groovy Api  Tutorial

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

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

As String in Java, String in Groovy is immutable.

Working with String

Page 9: Groovy Api  Tutorial

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

Page 10: Groovy Api  Tutorial

“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

Page 11: Groovy Api  Tutorial

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

Page 12: Groovy Api  Tutorial

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

Page 13: Groovy Api  Tutorial

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

Page 14: Groovy Api  Tutorial

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

Page 15: Groovy Api  Tutorial

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

Page 16: Groovy Api  Tutorial

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

Page 17: Groovy Api  Tutorial

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

Page 18: Groovy Api  Tutorial

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

Page 19: Groovy Api  Tutorial

Details about calling a method

Groovy Object

Page 20: Groovy Api  Tutorial

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

Page 21: Groovy Api  Tutorial

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

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

args -> //…}

Intercepting Methods