The original article was first published in the wechat public number: Jzm-blog, welcome to pay attention to the exchange!
Gradle is a dynamic language based on the JVM. Groovy has a syntax similar to Java’s. Groovy is fully compatible with Java. Gradle files are based on Groovy syntax. Groovy is Java compatible, so you can write Java code in Gradle files. Gradle files support closures, DSLS, and so on. Groovy is a very flexible dynamic scripting language.
- First introduction to Gradle series
- Gradle: Groovy Basics
- Gradle series build script basics
- Gradle series understanding Gradle tasks
- Gradle plugin for Gradle series
- Gradle series of Java Gradle plug-ins
- Gradle series of Android Gradle plugin
- Gradle series Android Gradle base configuration
- Android Gradle advanced Configuration
- The Gradle series builds Maven private server libraries from scratch
Let’s take a look at some Groovy basics for Gradle.
- string
- A collection of
- methods
- JavaBean
- About the closure
string
Said a Groovy features, in Groovy semicolon is not required, the single quotes is double quotation marks is a string constants are defined, the difference is single quotation marks are purely string constants, don’t do arithmetic expressions of the string on the inside, and use double quotes to define string constants can be used to do relevant legal expression, The test code is as follows:
task stringTest{
// use the def keyword to define variables,
def str1 = "Double quotes"
def str2 = 'Single quotes'
println "String defined by double quotes:"+str1
println "String defined by double quotes:"+str1.class
println "String defined by single quotes:"+str2
// The variable changes dynamically
str1 = true;
println "String defined by double quotes:"+str1.class
// Use the $operator
println "Double quoted string: ${str1}"
// Leave out the brackets when there is only one variable
println "Double quoted string: $str1"
// Strings defined by single quotes cannot be evaluated using expressions
println 'Single quoted string: $str2'
}
Copy the code
The following is the result:
PS E:\Gradle\study\Groovy> Gradle stringTest > Configure projectclass java.lang.StringString defined by single quotes: string defined by single quotes and double quotes:class java.lang.BooleanString defined by double quotes:trueString defined by double quotes:trueString defined by single quotes: $str2
BUILD SUCCESSFUL in 1s
Copy the code
A collection of
Groovy also has the concept of collections. Let’s take a look at the common List and Map operations.
Groovy lists are defined in the same way as arrays are defined in Java.
task list{
/ / define the List
def list = [1.2.3.4.5.6];
def weekList = ['Monday'.'Tuesday'.'Wednesday'.'Thursday'.'Friday'.'Saturday'.'Sunday'];
println "List type:"+list.class
println "WeekList type:"+weekList.class
// Access the elements in the collection
println 'First element:'+list[0]// Access the first element
println 'Second element:'+list[1]// Access the second element, and so on
println 'Last element:'+list[- 1]// Access the last element
println 'Penultimate element:'+list[2 -]// Accesses the penultimate element, and so on
println 'A range of elements:'+list[2.4.]// Access a range of elements, and so on
// Use each to iterate over the elements in the collection
weekList.each{
// Use it as the element variable of the iteration
println it
}
}
Copy the code
The following is the result of the above code, for reference:
PS E: Gradle\study\Groovy\ListMap> Gradle list > Configure project:class java.util.ArrayList
weekListThe type of:class java.util.ArrayListFirst element: 1 Second element: 2 Last element: 6 Penultimate element: 5 Elements in a range: [3, 4, 5] Monday Tuesday Wednesday Thursday Friday Saturday SundayBUILD SUCCESSFUL in 2s
Copy the code
How to define a Map in Groovy? Groovy maps are also key-value pairs.
task map{
/ / define the Map
def map = ['name':'Groovy'.'age':10];
println "Map type:"+map.getClass().name;
// Access the Map elements
println map.name;
println map['name'];
// Iterate over the elements in the Map
map.each{
println "Key:${it.key},value:${it.value}"}}Copy the code
The following is the result of the above code, for reference:
PS E:\Gradle\study\Groovy\ListMap> gradle map > Configure project : Groovy Key:name,value:Groovy Key:age,value:10
BUILD SUCCESSFUL in 2s
Copy the code
So much for Groovy’s collection.
methods
The method in Groovy is similar to the method in Java, except that it is written more flexibly. A return is not required in Groovy, and when a return is not written, Groovy returns the last line of code as the method’s return value. A code block is a block of code surrounded by curly braces. Groovy can pass a code block as a parameter, as shown in the previous section on traversal of collections:
task method{
// method call
methodA(1.2)
methodA 1.2
// Get the result returned by the method
def a = methodA 10.20
println 'Return result of method:'+a
// Code blocks are passed as arguments
def list = [1.2.3.4.5];
list.each(
// Closure arguments
{
// println it})//Groovy specifies that if the last argument to a method is a closure, it can be placed directly outside the method
list.each(){
// println it
}
// Short form
list.each{
println it
}
}
// Method definition
def methodA(int a, int b){
println a + b
// Return statements are not required in Groovy. By default, the result of the last line of code is returned
a + b
}
Copy the code
Here is the code reference above as follows:
PS E:\Gradle\study\Groovy\Method> gradle method
> Configure project :
3
3
30Get the result returned by the method:30
1
2
3
4
5
BUILD SUCCESSFUL in 2s
Copy the code
JavaBean
Javabeans in Groovy are more flexible than those in Java, and you can use Javabeans directly. Property to obtain and modify JavaBean property values, without using the corresponding Getter and Setter methods, directly view the code:
task javaBean{
// Define javabeans in Groovy
Student student = new Student()
student.name = "Groovy"
student.age = 10
student.setName("Gradle")
println "The name is:"+student.name
// Cannot call the Getter method to get the value
// println "the name is: "+student.getName
println ${student.age}"
println "The score is:"+student.score
}
class Student{
private String name
private int age
// The property corresponding to the defined Getter method can be called directly
public String getScore(){
100
}
// Getters and setters for properties
public String setName(String name){
this.name = name
}
public void getName(){
name
}
}
Copy the code
Here is the result of the above code:
PS E:\Gradle\study\Groovy\JavaBean> Configure project:10Scores are:100
BUILD SUCCESSFUL in 2s
Copy the code
closure
Closures are a feature of most scripting languages, such as JavaScript and Groovy. A closure is a block of code surrounded by curly braces.
Closures and their parameter passing
Let’s see how to define a closure and pass its parameters directly to the code:
task closure{
// Custom closure execution
mEach{
println it
}
// Pass parameters to the closure
mEachWithParams{m,n -> //m,n -> separate the closure parameters from the body
println "${m} is ${n}"}}//1. Define a method with the closure argument to accept closure
//2. Closure execution is the execution of the code inside curly braces
//3. The closure argument is the I in the closure argument, which is the it variable by default
def mEach(closure){
for(int i in 1.. 5){
closure(i)
}
}
// Pass parameters to the closure
def mEachWithParams(closure){
def map = ["name":"Groovy"."age":10]
map.each{
closure(it.key, it.value)
}
}
Copy the code
The above code defines the closure and how to pass the parameters of the closure. When the closure has only one parameter, the default is “IT”; otherwise, when the closure has multiple parameters, the parameters need to be defined.
PS E:\Gradle\study\Groovy\Closure> gradle delegate
> Configure project :
1
2
3
4
5
name is Groovy
age is 10
BUILD SUCCESSFUL in 2s
Copy the code
Commissioned by the closure
The power of Groovy closures is that they support delegation of closure methods. Groovy closures have three properties: ThisObject, Owner, delegate. When a defined method is called in a closure, these properties determine which object will execute the method. By default, owner and delegate are equal, where delete can be modified. Many of the functions of closures in Gradle are implemented by modifying the delegate. Here are some of the differences between these three properties by defining a closure and a method, printed:
// Closure delegate
task delegate{
new Delegate().test{
//Groovy closure properties: thisObject, owner, delegate
println "thisObject:${thisObject.getClass()}"
println "owner:${owner.getClass()}"
println "delegate:${delegate.getClass()}"
// Closures default it
println "Closure default it:"+it.getClass()
ThisObject is the first method to be used
method()
// methods in closures
it.method()
}
}
def method(){
println "mththod in root:${this.getClass()}"
}
class Delegate{
def method(){
println "mththod in Delegate:${this.getClass()}"
}
/ / closures
def test(Closure<Delegate> closure){
closure(this); }}Copy the code
The following is the result of the above code, for reference:
PS E:\Gradle\study\Groovy\Closure> gradle delegate
> Configure project :
thisObject:class build_3ajca04o1rprxygcsq0ajvt7i
owner:class build_3ajca04o1rprxygcsq0ajvt7i$_run_closure2
delegate:class build_3ajca04o1rprxygcsq0ajvt7i$_run_closure2The closure of the defaultit:class Delegate
mththod in root:class build_3ajca04o1rprxygcsq0ajvt7i
mththod in Delegate:class Delegate
BUILD SUCCESSFUL in 2s
Copy the code
ThisObject calls method() instead of owner or delegate when calling method() in a closure. ThisObject is used to handle method execution first in the closure. You can also see that the owner and delegate are the same, but the owner has higher priority than the delegate, so the closure’s methods are processed in this order: thisObject > Owner > Delegate.
Gradle normally assigns a delegate to the current IT. This allows us to manipulate it using the delegate object. Specify the closure’s delegate and set the delegate to precedence, so that the delegate object executes its methods.
task student{
configStudent{
println "Current it: ${it}"
name = "Groovy"
age = 10
getInfo()
}
}
class Student{
String name
int age
def getInfo(){
println "name is ${name}, age is ${age}"}}def configStudent(Closure<Student> closure){
Student student = new Student()
// Set the delegate object to the currently created Student instance
closure.delegate = student
// Set the delegate mode to take precedence if the handler of the method inside the closure is thisObject
closure.setResolveStrategy(Closure.DELEGATE_FIRST)
// Set the IT variable
closure(student)
}
Copy the code
The following is the result of the above code, for reference:
PS E:\Gradle\study\Groovy\Closure> Gradle student > Configure project: current it: Student@18f6d755 name is Groovy, age is10
BUILD SUCCESSFUL in 2s
Copy the code
conclusion
The purpose of learning Groovy is to deepen the understanding of Gradle building tools. Above, I have a preliminary understanding of Groovy from five aspects. If necessary, I will look at the advanced uses of Groovy. You can follow the official account: Jzman-blog to communicate and learn together.