加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Groovy基础入门

发布时间:2020-12-14 17:02:26 所属栏目:大数据 来源:网络整理
导读:1. ?? 从例子开始 a) ??????? 目的:演示 Groovy 的一些简单特性。 ? b) ??????? 代码: class GTest1{ ???? GTest1() hello(name){ println( "Hello ${name}" ); println( "Hello " +name); } static void main(args) { t = new GTest1(); t.hello( "nick"

1.?? 从例子开始

a)??????? 目的:演示Groovy的一些简单特性。

?

b)??????? 代码:

class GTest1{

???? GTest1()

hello(name){

println("Hello ${name}");

println("Hello "+name);

}

static void main(args) {

t = new GTest1();

t.hello("nick");

}

}

?

c)??????? 输出:

Hello nick

Hello nick

?

d)??????? 说明:

????????????????????? i.????????????? 不需要声明变量类型。由于Groovy采用动态发现类型的技术,这有点类似于javascript中的做法,因此我们不需要显式声明我们的变量类型,他的类型将会在运行期被确定。

?????????????????? ii.????????????? 不需要声明访问控制符(publicprivate)。在Groovy当中,默认的访问控制符为public,因此当我们不显式进行声明时,他们的访问控制符即为public

??????????????? iii.????????????? 方法不需要声明返回值。Groovy当中,方法的返回值默认为Object

?????????????????? iv.????????????? 变量值引用。在hello方法内,我们调用了println方法,我们可以使用传统Java的通过“+”来连接参数,也可以通过新的,Groovy提供的${变量名}方式。

????????????????????? v.????????????? 表达式的结尾可以不用分号。Groovy允许程序员不在表达式的末尾添加分号。

?

2.?? 类定义

a)??????? 目的:演示在Groovy当中,如何进行类的定义和初始化。

?

b)??????? 代码:

class GTest2{

name;

job;

hello(name,job){

println("Hello ${name} ${job}");

println("Hello ${this.name} ${this.job}");

}

static void main(args) {

t1 = new GTest2(name:"cen",job:"it")

t1.hello("nick","student");

t2 = new GTest2(job:"it",name:"cen")

t2.hello("nick","student");

}

}

?

c)??????? 输出:

Hello nick student

Hello cen it

Hello nick student

Hello cen it

?

d)??????? 说明:

????????????????????? i.????????????? 属性值声明。由于Groovy不需要显式声明访问控制符和变量类型,因此,当我们为GTest2定义属性namejob时,也只需要提供变量名即可。

?????????????????? ii.????????????? 构造函数。声明类时,我们不要显式提供构造函数,Groovy会根据所有已声明的属性,为我们提供所有可用的构造函数,而当我们需要初始化一个类时,我们需要显式指明我们调用的是哪个构造函数。这里有一点特别有意思的是,在Java当中,由于方法只通过方法名和参数列表来区分,因此GTest2(String name,String job)GTest2(String job,String name)是不可能同时出现的,但在Groovy当中,GTest2(name:"cen",job:"it")GTest2(job:"it",name:"cen")都是有效的。

??????????????? iii.????????????? this引用。当方法的参数名和类的属性名相同时,我们可以使用this引用来指明我们所引用的值。

?

3.?? 类访问

a)??????? 目的:演示如何对类的属性,类方法和实例方法的调用。

?

b)??????? 代码:

class GTest3{

???? name;

???? hello(name){

???????? println "Hello ${name} ${this.name}";

???? }

???? static hi(name){

???????? println "Hi ${name}"

???? }

???? static void main(args) {

???????? GTest3.hi("nick");

???????? t = new GTest3(name:"cen");

???????? t.hello("a");

???????? println t.name;

???????? t.name = "cencen";

???????? println t.name;

???? }

}

c)??????? 输出:

Hi nick

Hello a cen

cen

cencen

?

d)??????? 说明:

????????????????????? i.????????????? 属性访问。由于默认的访问控制符为public,所以,我们无需通过get/set方法,即可直接对类的属性进行访问和修改。

?

4.?? 类继承与接口实现

a)??????? 目的:演示怎么在Groovy当中进行类的继承,与接口的实现。

?

b)??????? 代码:

接口代码:

public interface GTestInter {

??? public void bye(String name);

}

?

类代码:

class GTest4 extends GTest3 implements GTestInter{

???? bye(name){

???????? println("bye ${name}")

???? }

???? static void main(args) {

???????? t = new GTest4(name:"nick")

???????? t.hello("a")

???????? t.bye("b")

???? }

}

?

c)??????? 输出:

Hello a nick

bye b

?

d)??????? 说明:

????????????????????? i.????????????? 接口定义。在Groovy当中,不支持直接的定义接口。

?????????????????? ii.????????????? 接口实现。Groovy允许Groovy类像一般方式来实现Java当中已定义好的接口。

??????????????? iii.????????????? 类集成。在Groovy当中,类继承与Java当中的一致。

?

5.?? Closure

a)??????? 目的:ClosureGroovy增加的一个功能强大的机制,这里演示一部分的Closure使用。

?

b)??????? 代码:

class GTest5{

???? name;

???? job;

???? static void main(args) {

???????? t = new GTest5(name:"nick",job:"it");

???????? t.eachPropertyName({println("${it}")});

???? }

}

?

c)??????? 输出:

__timeStamp

job

class

metaClass

name

?

d)??????? 说明:

????????????????????? i.????????????? Closure与匿名内部类相似,她是匿名的方法。

?????????????????? ii.????????????? 缺省情况下,Closure有一个叫做it的参数。

??????????????? iii.????????????? eachXX()方法。这部分方法是Groovy为某些类额外增加的,对于ObjecteachProperty(),对于文件有eachLine()方法,对于集合有each()方法,这些方法提供了一种遍历对象内部属性的方法,这些方法都接收一个Closure为参数,因此,通过传入不同的Closure,我们可以很灵活的对类的内部情况进行查看。

?

6.?? Closure声明

a)??????? 目的:演示Closure的声明。

?

b)??????? 语法:{ [closureArguments|] statements }

?

c)??????? 代码:

class GTest6{

???? a;

???? hello(b){

???????? c = "c";

???????? return {print("${a} ${b} ${c}")}

???? }

???? static void main(args) {

???????? t = new GTest6(a:"a")

???????? cr = t.hello("b")

???????? cr.call()

???? }

}

?

d)??????? 输出:

a b c

?

e)??????? 说明:

????????????????????? i.????????????? Closure可以访问所有她所属定义范围内的变量。

?????????????????? ii.????????????? Closure可以通过call()方法被调用,即使她已经离开了声明她的范围,仍然可以访问到这些变量值。

?

7.?? 利用Closure实现多态

a)??????? 目的:演示如何通过Closure实现多态

?

b)??????? 代码:

class Animal{

???? action

???? hello(sound){

???????? action(sound);

???? }

}

?

dog = {sound | println("I am a dog ${sound}")}

cat = {sound | println("I am a cat ${sound}")}

?

a1 = new Animal(action:dog)

a2 = new Animal(action:cat)

a1.hello("wo")

a2.hello("miao")

?

c)??????? 输出:

I am a dog wo

I am a cat miao

?

d)??????? 说明:

????????????????????? i.????????????? Groovy中的类文件可以不需要main()方法,而照样可以执行。

?????????????????? ii.????????????? 通过传入不同的Closure,我们可以实现多态。

??????????????? iii.????????????? 对于Closure,我们可以通过名称直接调用,而不需要调用call方法,因此我们不能进行类似dog("wo")Closure初始化,因为这会直接导致Closure的调用。所以,这里我们绕了一个弯,通过hello的参数来调用Closure

?

8.?? 方法定义

a)??????? 目的:演示不在类内部的方法定义。

?

b)??????? 代码:

def foo(value) {

???????? ???? println "Calling function foo() with param ${value}"

}

foo(1)

?

c)??????? 输出:

Calling function foo() with param 1

?

9.?? 集合声明

a)??????? 目的:演示如何声明,访问以及修改集合中的元素。Groovy提供了四种集合类型,列表(List),范围(Range),映射表(Maps),字符串,数组(Array)。

?

b)??????? 代码:

class GTest9{

???? static void main(args) {

???????? list = [1,2,3,4]

???????? range = 'a'..'d'

???????? map = ["a":1,"b":2,"c":3]

???????? str = "Hello World"

????????

???????? println("=====before start=====")

???????? println("the value of list[1] is ${list[1]}")

???????? println("the value of range[1] is ${range[-1]}")

???????? println("the value of map.a is ${map.a}")

???????? println("the value of str[1] is ${str[1]}")

???????? println("=====before end=====")

????????

???????? list[1] = 5

???????? map.a = 5

????????

???????? println("=====after start=====")

???????? println("the value of list[1] is ${list[1]}")?????

???????? println("the value of map.a is ${map.a}")

???????? println("=====after end=====")??????

???? }

}

?

c)??????? 输出:

=====before start=====

the value of list[1] is 2

the value of range[1] is d

the value of map.a is 1

the value of str[1] is e

=====before end=====

=====after start=====

the value of list[1] is 5

the value of map.a is 5

=====after end=====

?

d)??????? 说明:

????????????????????? i.????????????? 我们不能对Range和字符串中的内容进行修改。

?????????????????? ii.????????????? Maps当中的关键字必须为字符串类型。

??????????????? iii.????????????? 我们除了可以使用正向索引访问集合以外,还可以使用反向索引(即负数)。

?

10.集合分片

a)??????? 目的:演示如何通过Range来实现对集合的切片。可以被进行切片的集合包括列表,字符串,数组和正则式。

?

b)??????? 代码:

class GTest10{

???? emit(col){

???????? for(i in col)

????????????? print i+" "

???????? println("")

???? }

?

???? static void main(args) {

???????? t = new GTest10()

????????

???????? list = [1,4]

???????? sublist = list[2,3]????????

???????? t.emit(sublist)???

????????

???????? str = "Hello World"

???????? substr = str[-1,-2,-3]

???????? t.emit(substr)

????????

???????? array = new int[]{1,4,5}

???????? subarray = array[3..1]

???????? t.emit(subarray)

???? }

}

?

c)??????? 输出:

3 4

d l r

4 3 2

?

d)??????? 说明:

????????????????????? i.????????????? 我们除了可以使用正向的切片之外,还可以使用逆向的切片(即b..a的范围)

?

11.流控制

a)??????? 目的:演示Groovy当中的特别的for操作,遍历操作和switch操作。通过上面的例子,我们可以看到Groovy使用了与JDK 5.0当中一致的for循环操作。而通过Groovy提供的eachXX()方法,我们可以对某些特定的类进行更简单的遍历。而对于switch操作,除了Java已经支持的switch类型外,Groovy还提供了一些额外的支持。

?

b)??????? 代码:

class GTest11{

???? static void main(args) {

???????? a = "123"

???????? switch(a){

????????????? case String:print("This is string")

????????????? break;

????????????? case Integer:print("This is integer")

????????????? break;

???????? }

???????? println("");

????????

???????? b = 1

???????? switch(b){

????????????? case 0..2:print("in 0..2");

????????????? break;

????????????? case 3..5:print("in 3..5");

????????????? break;

???????? }

???????? println("");

????????

???????? switch(b){

????????????? case [1,4]:print("in [1..4]");

????????????? break;

????????????? case [5,6,7,8]:print("in [5..8]");

????????????? break;

???????? }???

???? }

}

?

c)??????? 输出:

This is string

in 0..2

in [1..4]

?

d)??????? 说明:

????????????????????? i.????????????? Groovyswitch当中case的类型还可以是Class,集合,正则表达式。

?

12.文件操作

a)??????? 目的:演示Groovy下的文件读,写操作。

?

b)??????? 代码:

import java.io.*

?

bw = new File("test.txt").newWriter()

for(i in 0...10){

???? bw.writeLine(String.valueOf(i));

}

bw.flush();

bw.close();

file = new File("test.txt")

file.eachLine{print "${it}/t"}

?

c)??????? 输出:

0??? 1??? 2??? 3??? 4??? 5??? 6??? 7??? 8??? 9???

?

d)??????? 说明:

????????????????????? i.????????????? GroovyFile类提供了额外的方法,用于从File实例中直接获取输入,输出流和Reader/Writer

?????????????????? ii.????????????? GroovyReader/Writer提供额外的方法,用于直接读写文件。

??????????????? iii.????????????? GroovyFile提供额外的方法,用于遍历文件的内容。

?

13.命令行调用

a)??????? 目的:演示Groovy下如何创建Process,并调用其他exe命令。

?

b)??????? 代码:

p = "java".execute()

println("${p.text}");

?

c)??????? 输出:

Usage: java [-options] class [args...]

?????????? (to execute a class)

?? or? java [-options] -jar jarfile [args...]

?????????? (to execute a jar file)

?

where options include:

??? -client?? ? to select the "client" VM

??? -server?? ? to select the "server" VM

?

d)??????? 说明:

?

14.结束语:Groovy的强大不在于Groovy本身,而在于Groovy通过与其他已有工具的整合和改进来提高我们的工作效率。一个比较明显的使用是Groovy当中定义的XXXBuilder,这些预定义的Builder可以简化我们对DOMSAXAnt等接口和工具的处理和使用。而Builder的实现很大程度上依靠的就是Groovy提供的Closure机制,所以,总的来说,只有掌握好Closure,才能真正用好Groovy

对于,Groovy值得进一步研究的包括Groovy主页上提供的使用Groovy进行单元测试,使用Groovy进行Ant的定制,使用Groovy进行数据库查询,使用Groovy进行Swing界面设计,等等。

Groovy现在的版本是0.9beta,由于还没推出正式版,所以,网站上也只能提供一些基于例子的演示,期待正式版推出以后会附有详细的开发和使用文档。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读