Groovy Api Tutorial


Published on

  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • defhaha = "haha"def a = /asdasdas ${haha}/printlnhaha.getClass().nameprintlna.getClass().nameprintln "haha"[1..3]defnum = "012345678"printlnnum[-1 .. 0]for(str in 'abc'..'abz'){ print "$str "}
  • Groovy Api Tutorial

    1. 1. Groovy API<br />QIYI AD Team<br />Yan Lei<br />
    2. 2. You can define a variable without specifying TYPE<br />def user = new User()<br />You can define function argumentswithout TYPE<br />void testUser(user) { user.shout() }<br />Types in Groovy<br />1.1.getClass().name // java.math.BigDecimal<br />Multimethords<br />Example<br />Dynamic Type<br />
    3. 3. import java.util.*;<br />public class UsingCollection<br />{<br />public static void main(String[] args)<br />{<br />ArrayList<String> lst = new ArrayList<String>();<br />Collection<String> col = lst;<br />lst.add("one" );<br />lst.add("two" );<br />lst.add("three" );<br />lst.remove(0);<br />col.remove(0);<br />System.out.println("Added three items, remove two, so 1 item to remain." );<br />System.out.println("Number of elements is: " + lst.size());<br />System.out.println("Number of elements is: " + col.size());<br />}<br />}<br />Example<br />Please Give Result running on Java & Groovy<br />
    4. 4. One of The biggest contributions of GDK is extending the JDK with methods that take closures.<br />Define a closure<br />def closure = { println “hello world”}<br />Example<br />defpickEven(n, block){<br />for(inti = 2; i <= n; i += 2){<br /> block(i)<br />}<br />}<br />pickEvent(10, {println it})=== pickEvent(10) {println it} when closure is the last argument<br />def Total = 0; pickEvent(10) {total += it}; println total <br />Using Closures<br />
    5. 5. When you curry( ) a closure, you’re asking the parameters to be prebound.<br />Example<br />deftellFortunes(closure){<br />Date date = new Date("11/15/2007" )<br />postFortune= closure.curry(date)<br />postFortune "Your day is filled with ceremony"<br />postFortune "They're features, not bugs"<br />}<br />tellFortunes() { date, fortune -><br />println"Fortune for ${date} is '${fortune}'"<br />}<br />Curried Closure<br />
    6. 6. def examine(closure){<br />println "$closure.maximumNumberOfParameters parameter(s) given:"<br />for(aParameter in closure.parameterTypes) { println }<br />}<br />examine() { } // 1, Object<br />examine() { it } // 1, Object<br />examine() {-> } // 0<br />examine() { val1 -> } // 1, Object<br />examine() {Date val1 -> } // 1, Date<br />examine() {Date val1, val2 -> } // 2, Date, Object<br />examine() {Date val1, String val2 -> } // 2, Date, String<br />Dynamic Closures<br />
    7. 7. 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.<br />Example ??? <br />Closure Delegation<br />
    8. 8. Creating String with ‘, “(GStringImpl), ‘’’(multiLine) <br />getSubString using [] , “hello”[3], “hello”[1..3]<br />As String in Java, String in Groovy is immutable.<br />Working with String<br />
    9. 9. Problem<br />price = 568.23<br />company = 'Google'<br />quote = "Today $company stock closed at $price"<br />println quote<br />stocks = [Apple : 130.01, Microsoft : 35.95]<br />stocks.each { key, value -><br />company = key<br />price = value<br />println quote<br />}<br />Why ? <br />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.<br />Solution<br />Using closure<br />quote = “Today ${->company} stock closed at ${->price}”<br />GString Lazy Evaluation Problem<br />
    10. 10. “hello world” -= “world” <br />for(str in ‘abc’..’abz’){ print “${str} ”}<br />Regular Expressions<br />Define pattern : def pattern = ~”[aAbB]”<br />Matching<br />=~ , ==~<br />“Groovy is good” =~ /g|Groovy/ //match<br />“Groovy is good” ==~ /g|Groovy/ //no match<br />('Groovy is groovy, really groovy'=~ /groovy/).replaceAll(‘good' )<br />String Convenience Methods<br />
    11. 11. def a = [1,2,3,4,5,6,7] // ArrayList<br />Def b = a[2..5] // b is an object of RandomAccessSubList<br />Using each for iterating over an list<br />a.each { println it }<br />Finder Methords: find & findAll<br />a.find {it > 6} //7 return the first match result<br />a.findAll {it > 5} //[5,7] return a list include all matched members<br />Convenience Method<br />collect<br />inject<br />join<br />flatten<br />*<br />List<br />
    12. 12. def a = [s:1,d:2,f:3] //LinkedHashMap<br />fetch value by Key: a.s, a[“s”]<br />a.each {entry -> println “$entry.key : $entry.value” }<br />a.each{key, value -> println“$key : $value” }<br />Methods<br />Collect, find, findAll<br />Any, every<br />groupBy<br />Map<br />
    13. 13. The dump and inspect Methods<br />dump( ) lets you take a peek into an object.<br />Println“hello”.dump()<br />java.lang.String@5e918d2 value=[h, e, l, l, o] offset=0 count=5 hash=99162322<br />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.<br />Object Extensions<br />
    14. 14. identity: The Context Method<br />lst = [1, 2]<br />lst.identity {<br />add(3)<br />add(4)<br />println size() //4<br />println contains(2) // true<br />println "this is ${this}," //this is Identity@ce56f8,<br />println "owner is ${owner}," //owner is Identity@ce56f8,<br />println "delegate is ${delegate}." //delegate is [1, 2, 3, 4].<br />}<br />Object Extensions<br />
    15. 15. Sleep: suppresses the Interrupted-Exception. <br />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.<br />new Object().sleep(2000) {<br />println "Interrupted... " + it<br />flag //if false, the thread will sleep 2 second as if there is no interruption<br />}<br />Object Extensions<br />
    16. 16. class Car{<br />int miles, fuelLevel<br />void run(){println “boom …”}<br />Void status(int a, String b) {println“$a --- $b”}<br />}<br />car = new Car(fuelLevel: 80, miles: 25)<br />Indirect Property Access<br />println car[“miles”]<br />Indirect Method Invoke<br />car.invokeMethod(“status”, [1,”a”] as Object[])<br />Object Extensions<br />
    17. 17. Overloaded operators for Character, Integer, and so on. Such as plus( ) for operator +, next( ) for operator++, and so on.<br />Number (which Integer and Double extend) has picked up the iterator methods upto( ) and downto( ). It also has the step( ) method.<br />Thread.start{} & Thread.startDaemon()<br />java.lang extensions<br />
    18. 18. Read file<br />println new File('thoreau.txt' ).text<br />new File('thoreau.txt' ).eachLine { line ->println line}<br />println new File('thoreau.txt' ).filterLine { it =~ /life/ }<br />Write file<br />new File("output.txt" ).withWriter{ file -><br /> file << "some data..."<br />}<br /> Extensions<br />
    19. 19. Details about calling a method<br />Groovy Object<br />
    20. 20. Use MetaClass to modify a class at runtime<br />Dynamic Adding or modifying Method<br />A.metaclass.newMethod= { println “new method”}<br />Dynamic Adding or modifying variable<br />A.metaClass.newParam = 1<br />After these, U can<br />new A().newMethod()<br />println new A().newParam<br />MetaClass<br />
    21. 21. Implements GroovyInterceptable & define method invokeMethod(String name, args)<br />Using MetaClass<br />define a closure for metaclass<br />Car.metaClass.invokeMethod = { String name, args-><br />//…<br />}<br />Intercepting Methods<br />