Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Groovy of Gradle Learning Notes

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >

Share

Shulou(Shulou.com)06/01 Report--

Gradle is a project automation build tool based on the concepts of Apache Ant and Apache Maven. It uses a Groovy-based domain-specific language (DSL) to declare project settings, abandoning all kinds of tedious XML-based configurations. Gradle's build scripts build.gradle and setting.gradle are executable Groovy scripts (although they cannot be run in the Groovy runtime environment, because the above .gradle files need to be run by calling gradle's api and the suffix is not .groovy). The following is a brief introduction to the knowledge of Groovy language which is less than Gradle by comparing with Java.

1. What is Groovy?

Groovy is a dynamic language based on Java virtual machine. This dynamic language has features similar to those found in Python, Ruby, and Smalltalk and can be used as a scripting language for the Java platform. The syntax of Groovy is so similar to Java that most Java code is correct Groovy code.

Java developers provide the most popular programming language features in modern times, and the learning cost is very low.

Support DSL (Domain Specific Languages Domain definition language) and other concise syntax to make your code easy to read and maintain.

Seamlessly integrate all existing Java objects and class libraries.

Then compiled into Java bytecode, so that you can use Groovy anywhere you use Java.

2. Java VS Groovy

The following shows the Java and Groovy with the same meaning in the Groovy environment

Code piece, and then explain the difference between the two

Java

Public class Me {private String name; public Me (String name) {this.name = name;} public String getName () {return name;} public void setName (String name) {this.name = name;}}

Groovy

Class Me {String name public Me (String name) {this.name = name}}

From the above, we can see that the Groovy version is more concise. The following shows the characteristics of Groovy relative to Java:

The semicolon after the expression; is optional

Each class, constructor, method access property defaults to public

The value of the last expression in the method body is used as the return value, which means that the return statement is optional

The Groovy compiler automatically adds the getter/setter method, so you don't need to add it manually.

The properties of the class can be passed through the period. Get and assign, the bottom layer is by calling the automatically generated getter/setter method.

In Groovy, compare two instances with = =. The underlying call is the equals () method, which can also avoid possible null pointer exceptions.

3. Groovy Advanced Features 3.1 optional type definition

As a dynamic language, all variables in groovy are objects. When declaring a variable, groovy does not require mandatory type declaration, but only requires the keyword def before the variable name. The def keyword is used as a placeholder of java.lang.Object to determine the type at run time.

/ / assert for assertion checking) def var = 1assert var.class = = java.lang.Integervar = "bupt" assert var.class = = java.lang.String3.2 optional parentheses

In Groovy, if the method signature requires at least one parameter, the method call can omit parentheses.

Def callMe (name) {new Me (name)} callMe ('faith') callMe' faith'println ("we could not live without faith!") println "we could not live without faith!" 3.3Strings

In Groovy, there are three different ways to define strings. Single quotation marks usually create String types equivalent to Java; the second, like Java, is enclosed in double quotes, and cross-line strings are enclosed in three double quotes.

The following points are explained:

Like java, you can use the + sign to connect the string

Strings in double quotes in Groovy can be interpolated with variables or in expressions, indicated by $and curly braces {}. At run time, Groovy evaluates the expression and forms a string. This string is called GString in Groovy. The difference between S4 S5 and single quotation marks can also be seen in the following example.

Def S1 = 'bupt'def S2 = "bupt" def S3 = "bupt" def S4 = "hello" + "${S1}" def S5 = "hello" +' ${S1} 'println s1println s2println s3println S4

Output:

Buptbuptbupthello bupthello ${S1} 3.4 naming parameters

A feature that reduces input is provided in Groovy called named parameters (Named Parameter). GroovyBean can be built by passing property names and values separated by colons in constructor calls. Such as:

Class Me {String name} Me me = new Me (name: "faith") println me.nameme.name = 'bupt'println me.name

Output:

Faith

Bupt

Externally, it seems that the null constructor is called first, and then the corresponding setter method is used to set the value. Therefore, what we directly imagine should be equivalent to the following Java code:

Me me = new Me (); me.setName ("faith"); 3.5 closures

Before introducing closures, let's talk about a few features of code blocks in Groovy.

3.5.1 Code Block

The variable scope of groovy is similar to that of java, and variables declared inside the code block cannot be called by external access.

For Groovy Script, variables defined with def are not visible to binding.variables. There is no definition such as def that can be binding.variable. The parameter name is accessed.

For the first rule, there is an exception. When a variable has no definition such as def, the variable is globally valid.

Code blocks can be nested, such as try code blocks, which is the same as Java.

Introduction to try {h = 9assert binding.variables.h = = 9} assert h = = 9assert binding.variables.h = = 93.5.2closures

Closures are blocks of code of type groovy.lang.Closure enclosed in curly braces {}. Similar to Python's lambda expression, a closure can be assigned to a variable, passed as an argument to a method, and called like a normal method.

It seems that a closure is similar to a method in that you need to define parameters and statements to execute, and it can also be called by name. However, closure objects can be passed as parameters. Second, the closure can also be unnamed (of course, as a price, it can only be executed once when the closure is defined)

3.5.3 closure parameters

1. Display parameter closures:

The parameter declaration of the closure is written before the'- > 'symbol, and the standard way to call the closure is: the closure name. Call (closure parameter).

Def toTriple = {n-> n * 3} assert toTriple.call (5) = = 15

two。 Hermit parameter closure:

For the single existing parameter it can not be declared, the direct use of it,it has a special meaning in Groovy; if and only if there is only one parameter in the closure, and there is no declaration, it has the function of unique parameter reference; if the closure c is a parameterless closure, then its standard calling method is c.call (), and its concise calling method is c ().

C = {it*3} assert c ('run') = =' runrunrun' def a = 'coffee'def c = {def b =' tea' a + 'and' + b} assert c () = = 'coffee and tea'

3. Closure implied parameter

Parameter indicates the default parameter name of it. If no parameter is passed in the call, it is nullthis, just like Java, which is a reference to the class in which the closure is defined. No matter how many layers of closure are nested, this points to the top class. The object of an owner closed closure (if there is only one layer of closure is this, and if there is a multi-layer closure nested is the upper closure containing this closure) the default value of delegate is owner, but it can be changed, as described later.

4. The parameter names in the closure cannot be duplicated, except for it.

Def name= 'cup'def c = {name- > println (name)} / / a compile error when uncommented://current scope already contains name' name'c= {def d = {2 * it}; 3 * d (it)} assert c (5) = = 30

5. Closures can be nested.

Def gcd / / predefine closure namegcd= {mdirection n-> m%n==0? N: gcd (nmemm% n)} assert gcd (28,35) = = 73.5.4 closure return value

A closure always has a return value, which is the last line of the closure statement, regardless of whether the statement is named the return keyword or not. If the last sentence of the closure has no value, return null

3.5.5 assignment and call

Assignment: a closure is assigned to a variable, which is consistent with the assignment between variables.

Def ctry {def a = 'sugar' c = {a} / / a closure always returns its only value} assert c () =' sugar'def d = c / / we can also assign the closure to another variableassert d () = = 'sugar'

Call: calling the method of the closure is tantamount to creating an instance of the closure. For different instances created by the same closure, their objects are different.

C = {def e = {'milk'}; e} d = cassert c = = dv1 = c () v2 = c () assert v1! = v23.5.6 closure delegate

The usage of delegate delegation

Delegate delegation is a common design pattern, but it is relatively complicated to implement it in java. Groovy has implemented delegate pattern directly in GroovyObject, so it is very convenient to apply delegate in groovy.

Let's take a look at an example of a father dog asking an old cat to look after his dog son playing games:

Class Dog {def play = {"wang wang!"} def childmind = {println delegate.play ();}} class Cat {def play = {"mi mi!"}} def dog = new Dog () def cat = new Cat () dog.childmind () dog.childmind.delegate = cat;dog.childmind ()

3.6 Collection

Groovy supports the two most common java collections:

Java.util.Collection and java.util.Map.

3.6.1 Collection//1, define a collection def collect = ["a", "b", "c"] / / 2, add elements collect.add (1) to the collection The collect / / key,value parameter is used to accept the key / value of each element println "$key:$value"}) map.each {println it} / / it is a keyword that represents each element of the map collection map.each ({println it.getKey () + "-->" + it.getValue ()})

Print as follows:

Name:johnage:14sex:boyname=johnage=14sex=boyname-- > johnage-- > 14 sexist-> boy

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Network Security

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report