Groovy in action

Source: Internet
Author: User
Tags class generator

There are two ways to run the groovy class in JVM:

Compile all *. Groovy Java *. class files using yyc, put these *. class files in the Java class path, and load these classes through the Java class loader.

Use the groovy class loader to directly load at runtime *. groovy file and generate objects. In this way, no * is generated *. class, but a java. lang. instance of the Class Object. (Java's dynamic compilation and Loading Function)

Groovy enhances Java at the source code level, but the bytecode is the same as Java.

The Groovy syntax is line-oriented, but the execution of groovy code is not like this. Unlike other scripting languages, groovy code is not interpreted and executed in one line.

Groovy Code is fully converted. A Java class is generated through the converter, which is the Adhesive Between groovy and Java. The format of the generated groovy class is the same as that of the Java bytecode.

Groovy class loaders can load classes from *. Groovy files (convert and generate classes before they are cached ).

Generate groovy class at runtime

1. myscript. Groovy is passed to the groovy Converter

2. the converter generates an abstract syntax tree (AST) to represent all the code in myscript. Groovy;

3. Groovy class generator generates Java bytecode Based on AST. According to the script content, the result may be multiple classes. Now the class can be used through the groovy class loader;

4. Java runtime calls the class generated in step 3 like calling a Java class myscript;

The class has been fully built before use and cannot be changed at runtime (it is not excluded that the class will be replaced at runtime after. Groovy is modified ).

Everything in groovy is an object, and all operators are processed as method calls.



Note that bigdecimal is the default non-integer type. Unless the specified suffix is float or double, bigdecimal is used.




How does groovy process the expected information:

There is no problem with the literal symbols (numbers, strings, and so on) in groovy. They are all objects and they are packed and unpacked only when passed to Java, operators are a quick way to call methods.

Operators are convenient methods (all objects in groovy and operators are convenient methods of object methods ):

"=" Or "equals" indicates whether the object is equal (with equal values), rather than pointing to the same object.

The purpose of implementing equals is to ensure that this object can be compared with a null object. By default, the equals operation does not throw nullpointerexception.



The Times method is only used for repeated operations. The upto method increments by a number, downto is to decrease by a number, and step is to increment by one step from one number to another.

In object-oriented language, method-object-pattern is usually used to simulate an action: Define an independent method interface for a purpose, the instance of this interface can pass a set of parameters to the method and then call this interface method.

A closure is a block of statements enclosed by curly braces. To pass parameters to the closure, the closure has an optional list of parameters. "->" indicates the end of the list.

The script allows the use of undeclared variables. In this case, the variables are assumed to be obtained from the binding attribute of the script. If no corresponding variables are found in the binding, the variables are added to the bindding, binding is a data storage that transfers variables between the script caller and the script.

The default attribute range has special meanings in groovy,When the attribute Declaration of the range modifier is not specified, groovy will generate the corresponding access method (getter method and setter method) as needed)


Defining the type of a variable is optional. In any case, the identifier does not have to be unique during declaration. When there is no type or modifier, Def must be used for replacement, in fact, Def is used to indicate that the attribute or variable has no type (although the internal part will be declared as the object type ).

Rewrite subscript operator:

Rewriting the get method means that the dot-fieldname operator is overwritten. rewriting the set method means that the field assignment operator is overwritten.

class PretendFieldCounter{public count = 0;Object get(String name){return 'pretend value';}void set(String name,Object value){count++}}class Test {static main(args) {def pretender = new PretendFieldCounter();println pretender.isNoField == 'pretend value';println pretender.count == 0;pretender.isNoFieldEither = 'just to increase counter'println pretender.count == 1}}

All results are true.

Chapter 5 Closure

A closure is a code block encapsulated as an object. In fact, a closure is like a method that can accept parameters and return values.

A closure is a common object.

Closure statement: Originally:
class Closure {static main(args) {Closure envelope = {person-> printf(person)}["a","b"].each(envelope);}}

It can be written as follows:

class Closure2 {static main(args) {["a","b"].each{printf(it)};}}

Use a closure as a method call for a single parameter (it is very common to pass a closure to a method in groovy without special rules .)If the closure only requires one parameter, groovy provides a default name -- it

Declare ClosureAfter a method call, place the closure code in a pair of curly brackets. The closure parameters and code are separated by arrows (->. The second way to declare a closure is to directly assign it to a variable:

def printer = {line -> println line}

Return Value of a Method

def Closure getPrinter(){return {line -> println line}}
Curly braces indicate that a new closure object is built.
Tip: brackets can be used to indicate that a new closure object or groovy code block has been constructed. The code block can be class, interface, static, object initialization code, and method body, it can also appear together with groovy keywords (if, else, synchronzied, for, while, switch, try, catch, and finally). Other forms of appearance are closures.The third way to declare a closure is to reuse an existing Declaration: A method. Method closures are restricted to an instance method, but can be overloaded during runtime.If the closure parameter is declared as a display type, the type check does not call the closure during compilation at runtime: A reference X points to a closure. You can use X. Call () to call the closure or a simple X ()
class CallingClosures {static main(args) {def adder = {x,y -> return x+y}assert adder(4,3) == 7assert adder.call(2,6) == 8}}


Closure with default values:

class Closure4 {static main(args) {def adder = {x,y=5 -> return x+y}assert adder(4,3) == 7assert adder.call(7) ==12}}

Typical closure call method: Number of closure parameters:

class Closure5 {def caller(def closure){closure.getParameterTypes().size()}void test(){assert caller{ one ->}  ==1assert caller{ one,two ->}  ==2}static main(args) {new Closure5().test()}}

Curry functions (functional programming)

class Closure6 {static main(args) {def configurator = { format,filter,line->filter(line)? format(line):null}def appender = {config,append,line ->def out = config(line)if(out) append(out)}def dateFormatter = {line -> "${new Date()}:$line"}def debugFilter = { line -> line.contains('debug')}def consoleAppender = { line -> println line}def myConf = configurator.curry(dateFormatter,debugFilter)def myLog = appender.curry(myConf,consoleAppender)myLog('here is some debug message')myLog('this will not be printed')}}

Use the iscase Method for classification

class Closure7 {static main(args) {assert [1,2,3].grep{ it < 3} == [1,2]switch(10){case {it%2 == 1} : assert false}}}

Curly braces show the closure declaration time, not the execution time.

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.