Sister school to teach Java: Groovy dynamic partner

 

00 origin, story

"Brother, I heard on a" multi-threaded "is CSDN Jiang Tao, founder of thumbs up?" Sanmei proposed to her "sister school to teach Java" column has been very concerned about.

"Ah, a little excited. At first thought it was a vest, I did not expect a real person!"

"In fact, Jiang Tao thumbs up article a lot, just a brother of it." Sanmei unexpectedly poured cold water played.

"You're right. But it did give me inject a new energy, Jiang Tao, after all, is the industry's big brother ah."

"Let us begin a new chapter of it! I continue to ask questions, continue to answer your brother." Sanmei can not wait.

01, brother, what is Groovy ah?

Sanmei ah, brother to hear you speak slowly ah.

Groovy is a dynamically typed object-oriented language, like Java, can be run on the JVM.

The reason that Groovy is "dynamic" type language, because Groovy syntax from Smalltalk and Ruby, providing simpler than Java, more flexible syntax, type checking can be performed dynamically at runtime.

Java is a fixed type of language, such as integer variables int a = 0;, string variables String s = "Wanger". But in Groovy, without specifying the type of the variable (optional), type of the variable is declared at the time (or return) determined.

For example, a plastic can be assigned to the variable a, and then followed by a character string assigned to the variable a.

a = 0;
a = "Wanger";

Although not specify a type, but to a shaping time 0 is assigned, it is assigned "Wanger" when a string type.

Groovy code can be perfectly compatible with the Java code that can be used as a supplement of Java. You can even Java programming on the Java platform with Groovy, use basically the same as using Java code.

Many Java developers really like Groovy code and the similarity of Java code. Because from the point of view of learning, if you know how to write Java code, you will know how to write Groovy code.

Groovy was able to get the favor of Java developers, the main reason is that Groovy code needed to complete the same task fewer than Java code, because Groovy has relaxed syntax (allows you to omit the semicolon) and some special features (such as JavaScript often mentioned in the closure).

02, brother, can look Hello World?

Sanmei, Hello World is a must. Just like you buy a bag, total first try, and then shop around, right?

Remember written in Java Hello World it?

public class Wanger {
    public static void main(String [] args) {
        System.out.println("Hello World");
    }
}

We then compile it:

javac Wanger.java

And then we run the precompiled categories:

java Wanger

Not surprisingly, then, you will see "Hello World" on the screen.

That if the Hello World Groovy to write it?

println "Hello World"

Hey, I have not been surprised to do?

1) Groovy syntax let loose we do not need to print "Hello World" simple definition of this class.

2) Groovy would be very smart for us in front of the println plus System.out.

3) main method is not needed.

Imagine code stored in Wanger.groovy file, you can skip the compilation stage run directly:

groovy Wanger.groovy

Why even do not need to compile it? Because Groovy scripting language belongs, it can be interpreted at run time. Of course, you can also follow the steps to compile and run:

groovyc Wanger.groovy
groovy Wanger

Groovy code using the compiler will produce groovyc standard Java byte code, and then may be run via the java byte code command.

Note that , as long as Groovy code running on the command line, you need first to Groovy's official website to download free installation package, and then unzip it into the configuration environment variable, just like the original that you configure your Java environment variables.

Download the following address:

https://groovy.apache.org/download.html

03, brother, how to install Groovy ah?

Sanmei ah, because the brother has been using Eclipse as an integrated development environment, so this installation is to Groovy Eclipse plug-in as an example.

The first step, open Eclipse, select the Help menu in the Eclipse Marketplace , groovy keyword search results as shown below.

The second step, click on the install button, check all the Feature Selection dialog box, and then click the Confirm button.

The third step, the license confirmation dialog box check the I at The Terms of the Accept at The License Agreement , click on the Finish button.

The fourth step, the installation is successful, restart Eclipse. At this time, you can create a Groovy project, and as shown below.

A fifth step, a test class to create a Groovy, check static void main (args) options, as shown in FIG.

The generated code is as follows:

package groovyTest

class Wanger {

    static void main(args) {

    }
}

This version of Java before HelloWorld surprisingly similar, but there is no public modifier, and no type parameter of the main method.

At this time, we joined in the main method println "Hello World":

package groovyTest

class Wanger {

    static void main(args) {
        println "Hello World"
    }
}

We can directly select Run As Java Application to run Groovy code, because Groovy is actually Java, but the syntax is different, in most cases will be shorter, but the Groovy code 100% compliance with the standard Java bytecode.

04, brother, Groovy Java does not have the characteristics which have it?

Sanmei ah, you are asked this question very place ah.

In most cases, Java developers prefer to use Groovy to replace some of the characteristics of Java in inelegant solution.

像 Groovy 中一些可以省略的语法,比如说:

  • 语句结束处的分号;
  • 返回语句的 return 关键字;
  • 方法参数两边的括号;
  • public 访问限定符;
  • ……

这些并不是 Java 开发者要学习 Groovy 这门新语言的动力,那是什么呢?

1)Groovy List

在 Java 中,List 的操作方法大致如下:

List<String> list = new ArrayList<>();
list.add("沉默");
list.add("王二");

for (String s : list) {
    System.out.println(s);
}

但在 Groovy 中,操作方法变得更加便捷了。

可以像定义数组一样定义 list,就像下面这样:

def list = ["沉默", "王二"];

向 list 中添加元素也变得多种多样:

list.add("勇士");
list << "猛龙";
list[4] = "火箭";

也可以像数组一样取出元素:

def wanger = list[1];

2)Groovy Map

在 Java 中,Map 的操作方法大致如下:

Map<String, String> map = new HashMap<>();
map.put("name", "沉默王二");

但在 Groovy 中,操作方法变得更加便捷了。

可以按照以下方法定义一个 Map:

def map = [name:"沉默王二", "age":18];

注意:Groovy 中的键不必是字符串(可以不带双引号)。

向 map 中添加元素也变得多种多样:

map.put("money", 10000000);
map.sex = "保密";
map["work"] = "自由职业";

取出元素可以使用 . 或者 []

map.money;
map["work"]

3)Groovy 闭包

JavaScript 开发者一定不会对下面这句话感到陌生:

当一个函数被创建并传递或从另一个函数返回时,它会携带一个背包,背包中是函数声明时作用域内的所有变量。

这句话里面的“背包”就对闭包的一个恰当的比喻。Groovy 的官网是这样描述闭包的:

A closure in Groovy is an open, anonymous, block of code that can take arguments, return a value and be assigned to a variable.

大致的意思就是说,Groovy 闭包是一个开放的、匿名的代码块,可以接受参数,并把返回值赋值给变量。

闭包的定义方式如下:

{ [closureParameters -> ] statements }

其中 [closureParameters] 是以逗号分隔的参数列表,statements 是 0 个或者多个 Groovy 语句。 -> 操作符用于将参数列表与 Groovy 语句隔开。

我们来用闭包遍历一下列表,方式如下:

list.each({ x -> println x});

其中 { x -> println x} 就是一个闭包,把它作为 each() 方法的参数就可以将 list 中的元素取出,并且打印出来。

另外,闭包还有一个默认参数 it,它不需要像 x 一样声明出来,于是遍历 list 的代码就变成了下面这样:

list.each({println it});

接下来,我们再来看一下遍历 map 的方法,就是像变魔法一样。

可以使用默认的 it 作为元素,it.key 为键,it.value 为值。

map.each { println it.key + it.value }

注意: each() 方法的 () 还可以省略。

还可以自定义变量 item 作为元素,item.key 为键,item.value 为值。

map.each { entry -> println entry.key + entry.value }

或者,直接使用 key 和 value。

map.each { key, val -> println  key + val }

我们来自定义一个闭包,就像下面这样:

def addX = { x ->
    return x + 1;
};

addX 是这个闭包的名字,它接受一个参数 x,返回 x + 1。然后,我们可以这样来调用闭包:

println addX(3);
println addX.call(addX(3));

闭包在 Groovy 中不仅是一个方法,也是一个对象,所以它既可以作为参数传递,也可以调用方法。

05、故事的未完待续

“二哥,Groovy 有这么多引人注目的特性,使得它成为了一门出色的可以和 Java 共用的语言。但用 Groovy 的人并不多呢?”三妹所有所思的问。

“三妹啊,这是一个好问题呢,不过答案也显而易见。下图来自于 Groovy 官网,可以看到很多大厂的名字:Google、IBM、Linkedin、SONY。”

“不过,我听说 Java 8 中出现的 Lambda 表达式也能写出和 Groovy 一样简洁灵活的代码,你能不能教教我呢?”三妹的眼睛里充满了期待。

“三妹,你竟然知道 Lambda表达式……”

 

Guess you like

Origin www.cnblogs.com/qing-gee/p/11022861.html