Your SlideShare is downloading. ×
0
Groovy Api  Tutorial
Groovy Api  Tutorial
Groovy Api  Tutorial
Groovy Api  Tutorial
Groovy Api  Tutorial
Groovy Api  Tutorial
Groovy Api  Tutorial
Groovy Api  Tutorial
Groovy Api  Tutorial
Groovy Api  Tutorial
Groovy Api  Tutorial
Groovy Api  Tutorial
Groovy Api  Tutorial
Groovy Api  Tutorial
Groovy Api  Tutorial
Groovy Api  Tutorial
Groovy Api  Tutorial
Groovy Api  Tutorial
Groovy Api  Tutorial
Groovy Api  Tutorial
Groovy Api  Tutorial
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Groovy Api Tutorial

1,799

Published on

0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,799
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
12
Comments
0
Likes
2
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
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 "}
  • Transcript

    • 1. Groovy API
      QIYI AD Team
      Yan Lei
    • 2. You can define a variable without specifying TYPE
      def user = new User()
      You can define function argumentswithout TYPE
      void testUser(user) { user.shout() }
      Types in Groovy
      1.1.getClass().name // java.math.BigDecimal
      Multimethords
      Example
      Dynamic Type
    • 3. 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
    • 4. One of The biggest contributions of GDK is extending the JDK with methods that take closures.
      Define a closure
      def closure = { println “hello world”}
      Example
      defpickEven(n, block){
      for(inti = 2; i <= n; i += 2){
      block(i)
      }
      }
      pickEvent(10, {println it})=== pickEvent(10) {println it} when closure is the last argument
      def Total = 0; pickEvent(10) {total += it}; println total
      Using Closures
    • 5. When you curry( ) a closure, you’re asking the parameters to be prebound.
      Example
      deftellFortunes(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
    • 6. def examine(closure){
      println "$closure.maximumNumberOfParameters parameter(s) given:"
      for(aParameter in closure.parameterTypes) { println aParameter.name }
      }
      examine() { } // 1, Object
      examine() { it } // 1, Object
      examine() {-> } // 0
      examine() { val1 -> } // 1, Object
      examine() {Date val1 -> } // 1, Date
      examine() {Date val1, val2 -> } // 2, Date, Object
      examine() {Date val1, String val2 -> } // 2, Date, String
      Dynamic Closures
    • 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.
      Example ???
      Closure Delegation
    • 8. Creating String with ‘, “(GStringImpl), ‘’’(multiLine)
      getSubString using [] , “hello”[3], “hello”[1..3]
      As String in Java, String in Groovy is immutable.
      Working with String
    • 9. Problem
      price = 568.23
      company = 'Google'
      quote = "Today $company stock closed at $price"
      println quote
      stocks = [Apple : 130.01, Microsoft : 35.95]
      stocks.each { key, value ->
      company = key
      price = value
      println 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
    • 10. “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
    • 11. 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
    • 12. 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
    • 13. 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
    • 14. identity: The Context Method
      lst = [1, 2]
      lst.identity {
      add(3)
      add(4)
      println size() //4
      println contains(2) // true
      println "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
    • 15. 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... " + it
      flag //if false, the thread will sleep 2 second as if there is no interruption
      }
      Object Extensions
    • 16. class Car{
      int miles, fuelLevel
      void run(){println “boom …”}
      Void status(int a, String b) {println“$a --- $b”}
      }
      car = new Car(fuelLevel: 80, miles: 25)
      Indirect Property Access
      println car[“miles”]
      Indirect Method Invoke
      car.invokeMethod(“status”, [1,”a”] as Object[])
      Object Extensions
    • 17. 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
    • 18. 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
    • 19. Details about calling a method
      Groovy Object
    • 20. 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
    • 21. Implements GroovyInterceptable & define method invokeMethod(String name, args)
      Using MetaClass
      define a closure for metaclass
      Car.metaClass.invokeMethod = { String name, args->
      //…
      }
      Intercepting Methods

    ×