加载中...

Groovy


其中 Y=Groovy

源代码下载: learngroovy-cn.groovy

Groovy - Java平台的动态语言。了解更多。

  1. /*
  2. 安装:
  3. 1) 安装 GVM - http://gvmtool.net/
  4. 2) 安装 Groovy: gvm install groovy
  5. 3) 启动 groovy 控制台,键入: groovyConsole
  6. */
  7. // 双斜线开始的是单行注释
  8. /*
  9. 像这样的是多行注释
  10. */
  11. // Hello World
  12. println "Hello world!"
  13. /*
  14. 变量:
  15. 可以给变量赋值,以便稍后使用
  16. */
  17. def x = 1
  18. println x
  19. x = new java.util.Date()
  20. println x
  21. x = -3.1499392
  22. println x
  23. x = false
  24. println x
  25. x = "Groovy!"
  26. println x
  27. /*
  28. 集合和映射
  29. */
  30. //创建一个空的列表
  31. def technologies = []
  32. /*** 往列表中增加一个元素 ***/
  33. // 和Java一样
  34. technologies.add("Grails")
  35. // 左移添加,返回该列表
  36. technologies << "Groovy"
  37. // 增加多个元素
  38. technologies.addAll(["Gradle","Griffon"])
  39. /*** 从列表中删除元素 ***/
  40. // 和Java一样
  41. technologies.remove("Griffon")
  42. // 减号也行
  43. technologies = technologies - 'Grails'
  44. /*** 遍历列表 ***/
  45. // 遍历列表中的元素
  46. technologies.each { println "Technology: $it"}
  47. technologies.eachWithIndex { it, i -> println "$i: $it"}
  48. /*** 检查列表内容 ***/
  49. //判断列表是否包含某元素,返回boolean
  50. contained = technologies.contains( 'Groovy' )
  51. // 或
  52. contained = 'Groovy' in technologies
  53. // 检查多个元素
  54. technologies.containsAll(['Groovy','Grails'])
  55. /*** 列表排序 ***/
  56. // 排序列表(修改原列表)
  57. technologies.sort()
  58. // 要想不修改原列表,可以这样:
  59. sortedTechnologies = technologies.sort( false )
  60. /*** 列表操作 ***/
  61. //替换列表元素
  62. Collections.replaceAll(technologies, 'Gradle', 'gradle')
  63. //打乱列表
  64. Collections.shuffle(technologies, new Random())
  65. //清空列表
  66. technologies.clear()
  67. //创建空的映射
  68. def devMap = [:]
  69. //增加值
  70. devMap = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy']
  71. devMap.put('lastName','Perez')
  72. //遍历映射元素
  73. devMap.each { println "$it.key: $it.value" }
  74. devMap.eachWithIndex { it, i -> println "$i: $it"}
  75. //判断映射是否包含某键
  76. assert devMap.containsKey('name')
  77. //判断映射是否包含某值
  78. assert devMap.containsValue('Roberto')
  79. //取得映射所有的键
  80. println devMap.keySet()
  81. //取得映射所有的值
  82. println devMap.values()
  83. /*
  84. Groovy Beans
  85. GroovyBeans 是 JavaBeans,但使用了更简单的语法
  86. Groovy 被编译为字节码时,遵循下列规则。
  87. * 如果一个名字声明时带有访问修饰符(public, private, 或者 protected),
  88. 则会生成一个字段(field)。
  89. * 名字声明时没有访问修饰符,则会生成一个带有public getter和setter的
  90. private字段,即属性(property)。
  91. * 如果一个属性声明为final,则会创建一个final的private字段,但不会生成setter。
  92. * 可以声明一个属性的同时定义自己的getter和setter。
  93. * 可以声明具有相同名字的属性和字段,该属性会使用该字段。
  94. * 如果要定义private或protected属性,必须提供声明为private或protected的getter
  95. 和setter。
  96. * 如果使用显式或隐式的 this(例如 this.foo, 或者 foo)访问类的在编译时定义的属性,
  97. Groovy会直接访问对应字段,而不是使用getter或者setter
  98. * 如果使用显式或隐式的 foo 访问一个不存在的属性,Groovy会通过元类(meta class)
  99. 访问它,这可能导致运行时错误。
  100. */
  101. class Foo {
  102. // 只读属性
  103. final String name = "Roberto"
  104. // 只读属性,有public getter和protected setter
  105. String language
  106. protected void setLanguage(String language) { this.language = language }
  107. // 动态类型属性
  108. def lastName
  109. }
  110. /*
  111. 逻辑分支和循环
  112. */
  113. //Groovy支持常见的if - else语法
  114. def x = 3
  115. if(x==1) {
  116. println "One"
  117. } else if(x==2) {
  118. println "Two"
  119. } else {
  120. println "X greater than Two"
  121. }
  122. //Groovy也支持三元运算符
  123. def y = 10
  124. def x = (y > 1) ? "worked" : "failed"
  125. assert x == "worked"
  126. //for循环
  127. //使用区间(range)遍历
  128. def x = 0
  129. for (i in 0 .. 30) {
  130. x += i
  131. }
  132. //遍历列表
  133. x = 0
  134. for( i in [5,3,2,1] ) {
  135. x += i
  136. }
  137. //遍历数组
  138. array = (0..20).toArray()
  139. x = 0
  140. for (i in array) {
  141. x += i
  142. }
  143. //遍历映射
  144. def map = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy']
  145. x = 0
  146. for ( e in map ) {
  147. x += e.value
  148. }
  149. /*
  150. 运算符
  151. 在Groovy中以下常用运算符支持重载:
  152. http://www.groovy-lang.org/operators.html#Operator-Overloading
  153. 实用的groovy运算符
  154. */
  155. //展开(spread)运算符:对聚合对象的所有元素施加操作
  156. def technologies = ['Groovy','Grails','Gradle']
  157. technologies*.toUpperCase() // 相当于 technologies.collect { it?.toUpperCase() }
  158. //安全导航(safe navigation)运算符:用来避免NullPointerException
  159. def user = User.get(1)
  160. def username = user?.username
  161. /*
  162. 闭包
  163. Groovy闭包好比代码块或者方法指针,它是一段代码定义,可以以后执行。
  164. 更多信息见:http://www.groovy-lang.org/closures.html
  165. */
  166. //例子:
  167. def clos = { println "Hello World!" }
  168. println "Executing the Closure:"
  169. clos()
  170. //传参数给闭包
  171. def sum = { a, b -> println a+b }
  172. sum(2,4)
  173. //闭包可以引用参数列表以外的变量
  174. def x = 5
  175. def multiplyBy = { num -> num * x }
  176. println multiplyBy(10)
  177. // 只有一个参数的闭包可以省略参数的定义
  178. def clos = { print it }
  179. clos( "hi" )
  180. /*
  181. Groovy可以记忆闭包结果 [1][2][3]
  182. */
  183. def cl = {a, b ->
  184. sleep(3000) // 模拟费时操作
  185. a + b
  186. }
  187. mem = cl.memoize()
  188. def callClosure(a, b) {
  189. def start = System.currentTimeMillis()
  190. mem(a, b)
  191. println "Inputs(a = $a, b = $b) - took ${System.currentTimeMillis() - start} msecs."
  192. }
  193. callClosure(1, 2)
  194. callClosure(1, 2)
  195. callClosure(2, 3)
  196. callClosure(2, 3)
  197. callClosure(3, 4)
  198. callClosure(3, 4)
  199. callClosure(1, 2)
  200. callClosure(2, 3)
  201. callClosure(3, 4)
  202. /*
  203. Expando
  204. Expando类是一种动态bean类,可以给它的实例添加属性和添加闭包作为方法
  205. http://mrhaki.blogspot.mx/2009/10/groovy-goodness-expando-as-dynamic-bean.html
  206. */
  207. def user = new Expando(name:"Roberto")
  208. assert 'Roberto' == user.name
  209. user.lastName = 'Pérez'
  210. assert 'Pérez' == user.lastName
  211. user.showInfo = { out ->
  212. out << "Name: $name"
  213. out << ", Last name: $lastName"
  214. }
  215. def sw = new StringWriter()
  216. println user.showInfo(sw)
  217. /*
  218. 元编程(MOP)
  219. */
  220. //使用ExpandoMetaClass增加行为
  221. String.metaClass.testAdd = {
  222. println "we added this"
  223. }
  224. String x = "test"
  225. x?.testAdd()
  226. //拦截方法调用
  227. class Test implements GroovyInterceptable {
  228. def sum(Integer x, Integer y) { x + y }
  229. def invokeMethod(String name, args) {
  230. System.out.println "Invoke method $name with args: $args"
  231. }
  232. }
  233. def test = new Test()
  234. test?.sum(2,3)
  235. test?.multiply(2,3)
  236. //Groovy支持propertyMissing,来处理属性解析尝试
  237. class Foo {
  238. def propertyMissing(String name) { name }
  239. }
  240. def f = new Foo()
  241. assertEquals "boo", f.boo
  242. /*
  243. 类型检查和静态编译
  244. Groovy天生是并将永远是一门动态语言,但也支持类型检查和静态编译
  245. 更多: http://www.infoq.com/articles/new-groovy-20
  246. */
  247. //类型检查
  248. import groovy.transform.TypeChecked
  249. void testMethod() {}
  250. @TypeChecked
  251. void test() {
  252. testMeethod()
  253. def name = "Roberto"
  254. println naameee
  255. }
  256. //另一例子
  257. import groovy.transform.TypeChecked
  258. @TypeChecked
  259. Integer test() {
  260. Integer num = "1"
  261. Integer[] numbers = [1,2,3,4]
  262. Date date = numbers[1]
  263. return "Test"
  264. }
  265. //静态编译例子
  266. import groovy.transform.CompileStatic
  267. @CompileStatic
  268. int sum(int x, int y) {
  269. x + y
  270. }
  271. assert sum(2,5) == 7

进阶资源

Groovy文档

Groovy web console

加入Groovy用户组

图书

[1] http://roshandawrani.wordpress.com/2010/10/18/groovy-new-feature-closures-can-now-memorize-their-results/ [2] http://www.solutionsiq.com/resources/agileiq-blog/bid/72880/Programming-with-Groovy-Trampoline-and-Memoize [3] http://mrhaki.blogspot.mx/2011/05/groovy-goodness-cache-closure-results.html


还没有评论.