JVM-based basic knowledge of Dynamic Language groovy

Source: Internet
Author: User
Tags grails

In the process of using Java, it is a little more difficult than the C # syntax, such as exceptions and get set. After all, Java has developed a lot longer than C, many problems were not taken into account at the beginning of the design. In order to forward compatibility, we had to keep a certain historical burden (such as generic processing, Java's erasure implementation is the subsequent compatibility considerations ). However, it is very convenient to use groovy grails in a recent project, especially the integration of groovy and Java is very convenient.

The following describes some basic knowledge about groovy for reference. The documentation of groovy itself is also comprehensive, but the length is too long. The following is a concise reference.

Official http://groovy.codehaus.org

Official Website definition: groovy is an agile dynamic language for the Java platform with your features that are supported Red by languages like python, Ruby and smalltalk, making them available to Java developers using a Java-like syntax.

Groovya Dynamic Language made specifically for the JVM.

Groovy was designed with the JVM in mind

Groovy does not just have access to the existing Java API; its groovy development kit (gdk) actually extends the Java API by adding new methods to the existing Java classes tomake them more groovy.

Groovy is a standard governed by the Java Community process (JCP) as Java specification request (JSR) 241.

The following describes the common groovySyntax, according to the usage of this few times, you can quickly get familiar with groovySyntax

1. The default imported namespace is automatic imports

Importjava. Lang .*;

Importjava. util .*;

Import java.net .*;

Import java. Io .*;

Import java. Math. biginteger;

Import java. Math. bigdecimal;

Importgroovy. Lang .*;

Importgroovy. util .*;

You do not need to introduce interfaces and classes in the above namespace.

2. Optional; semicolon optional semicolons

MSG = "hello"

MSG = "hello ";

3. Optional brackets optional parentheses

Println ("Hello world! ")

Println "Hello world! "

// Method pointer

Def pizza = new pizza ()

Def deliver = pizza. & deliver ()

Deliver

4. optional return value: Optional return statements

string getfullname () {

return" $ {firstname }$ {lastname} "

}

// equivalent code

string getfullname () {

" $ {firstname }$ {lastname} "

}

5. optional type declaration optional datatype Declaration (duck typing)

S =" hello "

def S1 =" hello "

string S2 =" hello "

printlns. class

println s1.class

println s2.class

6. Optional Exception Handling optional Exception Handling

// In Java:

Try {

Reader reader = new filereader ("/foo.txt ")

}

Catch (filenotfoundexception e ){

E. printstacktrace ()

}

// In GROOVY:

Def reader = new filereader ("/foo.txt ")

7. Operator Overloading

Operator Method

A = B or! = B a. Equals (B)

A + B a. Plus (B)

A-B a. Minus (B)

A * B a. Multiply (B)

A/B A. Div (B)

A % B a. Mod (B)

A ++ or ++ A. Next ()

A--or--A. Previous ()

A & B a. and (B)

A | B a. or (B)

A [B] A. getat (B)

A [B] = c a. putat (B, c)

A <B a. leftshift (B)

A> B a. rightshift (B)

A <B or A> B or a <= B or a> = B a. compareto (B)

8. Safe dereferencing (?)

S = [1, 2]

Println s ?. Size ()

S = NULL

Println s ?. Size ()

Println person ?. Address ?. Phonenumber // optional

9. autoboxing

Autoboxes everything on the specified y

Float F = (float) 2.2f

F. Class

Primitive type automatic packing

10. Groovy truth

// True

If (1) // any non-zero value is true

If (-1)

If (! Null) // any non-null value is true

If ("John") // any non-empty string is true

Map family = [Dad: "John", MOM: "Jane"]

If (family) // true since the map is populated

String [] SA = new string [1]

If (SA) // true since the array length is greater than 0

Stringbuffersb = new stringbuffer ()

SB. append ("hi ")

If (SB) // true since the stringbuffer is populated

// False

If (0) // zero is false

If (null) // null is false

If ("") // empty strings are false

Map family = [:]

If (family) // false since the map is empty

String [] SA = new string [0]

If (SA) // false since the array is zero length

Stringbuffersb = new stringbuffer ()

If (SB) // false since the stringbuffer is empty

11. Embedded quotes

Def S1 = 'My name is "Jane "'

Def S2 = "My name is 'jar '"

Def S3 = "My name is \" Jane \""

Each double quotation mark can represent a string.

12. heredocs (triple quotes)

S = ''' this is

Demo '''

Println s

Three single and double quotation marks

13. gstrings

Def name = "John"

Println "Hello $ {name}. Today is $ {new date ()}"

14. LIST/map shortcuts

Def versions ages = ["Java", "groovy", "jruby"]

Printlnages. Class

Def array = ["Java", "groovy", "jruby"] as string []

Def set = ["Java", "groovy", "jruby"] as set

Def empty = []

Printlnempty. Size ()

Ages <"Jython"

Println ages [1]

Printlnages. getat (1)

Ages. Each {println it}

Ages. Each {Lang->

Printlnlang

}

Ages. eachwithindex {Lang, I->

Println "$ {I }:$ {Lang }"

}

Ages. Sort ()

Ages. Pop ()

Ages. findall {It. startswith ("G ")}

Ages. Collect {It + = "is cool "}

// Spread operator (*)

Println ages *. touppercase ()

Def family = [Dad: "John", MOM: "Jane"]

Family. Get ("dad ")

Printlnfamily. Dad

Family. Each {k, V->

Println "$ {v} is the $ {k }"

}

Family. keyset ()

Import groovy. SQL. SQL

// Spread operator (*)

Defparams = []

Params <"JDBC: mysql: // localhost: 3306/test"

Params <"root"

Params <""

Params <"com. MySQL. JDBC. Driver"

Printlnparams

Defsql = SQL. newinstance (* Params)

// Defdb = [URL: 'jdbc: HSQLDB: Mem: testdb', user: 'sa ', password: '', Driver: 'org. HSQLDB. jdbcdriver']

// Defsql = SQL. newinstance (db. url, DB. User, DB. Password, DB. Driver)

Defsql = groovy. SQL. SQL. newinstance ('jdbc: mysql: // localhost: 3306/tekdays ', "root", '', 'com. mySQL. JDBC. driver ')

Printlnsql. Connection. Catalog

Put the mysql-connector-java-5.0.7-bin.jar In the groovy installation lib directory

15. Ranges

Def r = 1 .. 3

(1 .. 3). Each {println "bye "}

Def today = new date ()

Defnextweek = Today + 7

(Today... nextweek). Each {println it}

16. Closures and blocks

Def HI = {println "hi "}

Hi ()

Def Hello = {println "Hi $ {It }"}

Hello ("John ")

Defcalculatetax = {taxrate, amount->

Return amount + (taxrate * Amount)

}

Println "Total Cost :$ {calculatetax (0.055, 100 )}"

// Pre-bind

Defcalculatetax = {taxrate, amount->

Return amount + (taxrate * Amount)

}

Def tax = calculatetax. Curry (0.1)

[10, 20, 30]. Each {

Println "Total Cost :$ {tax (IT )}"

}

the length is a little long, but with this knowledge, it is very helpful for the deep use of groovy grails.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.