开始学习Groovy
内容主要来源于 http://www.ibm.com/developerworks/cn/java/j-groovygrails/index.html
本文主要涉及一些简单语法和概念
内容主要来源于 http://www.ibm.com/developerworks/cn/java/j-groovygrails/index.html
本文主要涉及一些简单语法和概念
- package study
- /**
- * Groovy的对象
- */
- public class GroovyObject{
- static void main(args){
- println 12.class //一切都是对象
- println '14'.class
- def 年份 = 2008 //可以使用中文变量
- println 年份
- }
- }
- /**
- * Groovy的语法
- */
- public class GroovySyntax{
- static void main(args){
- def g = new GroovySyntax()
- g.repeat('abc')
- g.repeat('xyz',2)
- }
- def repeat(val, repeat=5){
- for(i in 0..<repeat){ //如果使用0..repeat,则会多循环一次
- println val
- }
- }
- }
- /**
- * Groovy的集合
- */
- public class GroovyCollection{
- static void main(args){
- def range = 0..4
- println range.class //集合类 class groovy.lang.IntRange
- assert range instanceof List //断言
- def coll = ["Groovy", "Java", "Ruby"]
- assert coll instanceof Collection //col1是Collection的实例
- assert coll instanceof ArrayList //col1是ArrayList的实例
- //三种增加方法:
- coll.add("Python")
- coll << "Smalltalk" //<< 操作符被重载,以支持向集合添加项
- coll[5] = "Perl"
- coll.each { println it} //使用闭包遍历coll,it是关键字,下行和本行效果一样
- coll.each { param -> println(param)}
- def numbers = [1,2,3,4] //使用+ - 增删集合的内容
- assert numbers + 5 == [1,2,3,4,5]
- assert numbers - [2,3] == [1,4]
- def numbers1 = [1,2,3,4]
- assert numbers1.join(".") == "1.2.3.4" //连接数组的内容
- assert [1,2,3,4,3].count(3) == 2 //计算3的数量
- assert ["JAVA", "GROOVY"] == ["Java", "Groovy"]*.toUpperCase() // * 表示数组的每个项
- }
- }
- /**
- * Groovy的Hash
- */
- public class GroovyHashtable{
- static void main(args){
- def hash = [name:"Andy", "VPN-#":45] //Groovy会自动把name变成"name"
- assert hash.getClass() == java.util.LinkedHashMap
- hash.put("id", 23) //使用put方法
- assert hash.get("name") == "Andy"
- hash.dob = "01/29/76" //相当于.put方法
- assert hash.dob == "01/29/76"
- hash["gender"] = "male" //也可以使用[]代替put
- assert hash.gender == "male"
- hash.each{ param -> println(param.key); println(param.value)} //遍历map,注意,必须加;或者换行
- hash.each{ key, value -> println "${key} is ${value}" } //使用${}进行替换
- }
- }
- /**
- * Groovy的闭包
- */
- public class GroovyClosure{
- static void main(args){
- def excite = { word -> return "${word}!!" }
- assert "Groovy!!" == excite("Groovy")
- assert "Java!!" == excite.call("Java") //闭包可以传递给某变量,并且延时执行
- }
- }
- /**
- * Groovy的类
- */
- public class GroovyClass{
- static void main(args) {
- def sng = new Song(name:"Le Freak",
- artist:"Chic", genre:"Disco") //自动构造函数
- def sng3 = new Song()
- sng3.name = "Funkytown"
- sng3.artist = "Lipps Inc."
- sng3.setGenre("Disco") //也可以使用set或者属性设置值
- assert sng3.getArtist() == "Lipps Inc."
- sng3.setGenre "Disco" //还可以这样
- assert sng3.genre == "Disco"
- }
- String toString(){
- "${name}, ${artist}, ${genre}" //覆盖toString方法,最后一行默认是return语句
- }
- }
- public class Song{
- def name
- def artist
- def genre
- def getGenre(){
- genre?.toUpperCase() //使用?判断非空
- }
- }