Groovy common syntax Summary

Source: Internet
Author: User
Tags groovy script

Among the powerful features of groovy, closure and metaclass have been tried. Closure basically means that when the method or callback interface is used, advanced usage is useless, and there is no special benefit, when the callback interface is a provincial-defined interface, it is concise. metaclass specifically makes some metaclass for a module, which is similar to Gorm and adds save, update, delete and other methods. The difference is that Gorm is stored in the database, and the module I used is to call the restful service. It is not bad. If there is a need, it is not necessary to change the class and add a method to the class, it is still very suitable. However, in most cases, these advantages cannot be reflected. Up to now, I am still impressed with some groovy syntaxes and summarize some common syntaxes:

1. List, and map Initialization

This is the most commonly used. In Java, you have to create a list or map and add the elements one by one. Groovy is much more concise in syntax.

Define a list:

[Java] view plaincopy

List intlist = [1, 3, 5, 7, 9]

List stringlist = ['A', 'B', '']


Define a map:

[Java] view plaincopy

Map map = [A: 4, B: 'D']


When defining a map, for keys, if there is no special indication like in the above example, all keys are of the string type, and the key value is 'A', 'B ', the above example is equivalent

[Java] view plaincopy

Map map = ['A': 4, 'B': 'D']


In some cases, the key of the map may be a variable. In this case, we need to use parentheses to hold the key. For example

[Java] view plaincopy

String A = 'I am key'

Map map = [(a): 'I am value']


You can also define an empty list or map.

[Java] view plaincopy

List empty = []

Map empty = [:]

You need to know that the List instance created in this method is arraylist and the map instance is linkedhashmap.

2. Binary operators? :

Java inherits the question mark expression in C language. Binary operators are more streamlined question mark expressions. Form:

[Java] view plaincopy

Def result =? : B


If the condition is true, that is, if A is true or a has a value, result is a; otherwise, result is B.

3. Security placeholders

This is very useful and can avoid a lot of nullpointerexception, but it cannot be abused.

[Java] view plaincopy

Def result = OBJ ?. Property


In the code, obj is an object, and property is a familiar object. In this line of code, if obj is not null, the value of the property is returned. If obj is null, this will directly return null. Statements can be serialized all the time.

[Java] view plaincopy

Def result = ?. B ?. C ?. D...


4. Field operations

According to the standard of groovy bean, by default, all fields in the class will help generate a get method. Outside the class, even if you directly use the attribute name instead of the get method to get the value, you get the value through the get method. What if I want to get the property value directly? Field operators:

[Java] view plaincopy

Class {

String B

}

A A = new ()

A. B // get the value through the get Method

A. getb () // get the value through the get Method

[Email protected] // get the value directly


5. gstring

Java has a string, while groovy has a new gstring. The Groovy syntax is that string is enclosed in single quotes, and gstring is enclosed in double quotes. So groovy cannot directly define the char in Java.

String

[Java] view plaincopy

String S = 'this is a string'


Gstring

[Java] view plaincopy

Gstring S = "This Is A gstring"


The instance types defined in the two methods are different. Of course, gstring is not so simple. The strength of gstring is that it can be used as a template.

[Java] view plaincopy

String name = 'Count'

Int value1 = 23

Int value2 = 22

Gstring S = "the value of $ name is ${value1 + value2 }"

Println s


The final output is: the value of count is 55

The second to last line contains the key character $, $, which indicates to reference the variable value in the context. In the middle of $ {}, not only can the variable value be referenced, but also some operations can be added as an expression.

The last line is to convert gstring to string and then output.

String is a constant, but gstring is a variable. To be precise, $ in gstring only exists as a placeholder for a template. gstring stores references to that object, if the value of the referenced object changes, the value of gstring changes accordingly.

It should be noted that, even if the final string values of string and gstring in map are the same, they still exist as two keys. It is easy to understand, but it is easy to make mistakes. For example, writing single quotation marks into double quotation marks by mistake may cause this mistake.

6. Constructor

[Java] view plaincopy

Class classa {

String S1

Int I1

Classb CB

}

Class classb {

String S2

}

New classa (S1: 'Pro in A', I1: 5, CB: [S2: 'Pro in B '])


The above code can work. Groovy will create a classa instance and set 'Pro In a' and '5 to attributes S1 and i1. Even if you are familiar with CB for a complex type, the classb object will be created and set to CB. The S2 in classb is familiar with 'Pro in B 'of course.

We can see that the parameters in the constructor are similar to the definition of map. Indeed, it is also possible to pass in map.

[Java] view plaincopy

New classa ([S1: 'Pro in A', I1: 5, CB: [S2: 'Pro in B '])


This function is convenient for data model conversion. For example, the front-end JSON data is directly converted to map, and then the constructor is new. Note that if map has a property value that is not in a class, an error occurs.

7. astype

In groovy, such code may often be seen.

[Java] view plaincopy

String A = '78'

Int B = A as int

Print B


The second row has the keyword as. It can be seen that the function is to convert string type A to int type B. How does it work? It is very simple. It is to delegate this operation to the astype method of string. For example, string has the following method (just for example, this is not the case in the Code)

[Java] view plaincopy

Class string {

Object astype (class clz ){

If (clz = integer ){

Return integer. parseint (this)

} Else if (clz = gstring ){

Return "$ this"

} Else {

Return super. astype (clz)

}

}

}


Then, the string can be converted to the Int or gstring type using the as operator.

[Java] view plaincopy

String A = '45'

Int B = A as int

Gstring c = A as gstring


The preceding clz = gstring is valid and is equivalent to clz = gstring. Class in groovy.

8. Inspect and eval

Like eval in Javascript, Eval directly executes a groovy script and can be directly called using eval. Me (... script here.

Inspect is the eval inversion operation, that is, converting an object into a legal executable script (I understand it and have not carefully read the document ). I have never tried other objects, but all objects like map and list can be transferred out. This is enough. The data transferred from map and list is equivalent to JSON in Javascript in groovy. In the system, data can be directly transmitted as data. Although this is not recommended, I still insist that if the data only contains simple types such as map, list, number, and string, why not? (If there is a problem when the value in number is Nan or infinite, but it is easy to solve, you can see the other two methods in the eval class ). Hehe, I used this way, until I found a bug (http://stackoverflow.com/questions/7410252/groovy-inspect-handle-dollar-sign), unable to solve, I changed the implementation.

However, I still have a lot of expectations for this. If it is internal integration, there is no security problem, and there is no good JSON support, this method is still a good way.


9. Is Method

According to the definition of groovy, The = operation is equivalent to calling the equals method. In this way, we lose the operator that directly judges whether two objects are the same object. To determine whether the object is the same, call the is method, such as thisobject. Is (anotherobject ). This is very important, especially when the equals method of the overwrite object is used, some places in the code automatically generated by ECLIPSE cannot directly use =, but use the is method.


That's all. If you find more new things in the future, add them.


Groovy common syntax Summary

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.