基于JVM的动态语言Groovy 基础知识汇总

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
云数据库 RDS MySQL Serverless,价值2615元额度,1个月
简介: 在使用Java的过程中,和C#的语法相比有些还是比较麻烦,比如异常、get set等问题,毕竟Java的发展时间比C#长了很多,很多问题当初设计时没有考虑到,为了向前兼容,不得不保留一定的历史负担(如泛型的处理,java的擦除法实现就是后续的兼容考虑)。

在使用Java的过程中,和C#的语法相比有些还是比较麻烦,比如异常、get set等问题,毕竟Java的发展时间比C#长了很多,很多问题当初设计时没有考虑到,为了向前兼容,不得不保留一定的历史负担(如泛型的处理,java的擦除法实现就是后续的兼容考虑)。不过最近在一个项目中使用groovy grails感觉很是方便,特别groovy和java的集成十分的方便。

下面把groovy涉及的一些基础知识整理一下,供使用参考,groovy本身的文档也很全面,但篇幅太长,如下作为一个简明的参考。

官网 http://groovy.codehaus.org

官网定义:Groovy is an agile dynamic language for the Java Platform with many features that are inspired by languages like Python, Ruby and Smalltalk, making them available to Java developers using a Java-like syntax.

Groovya dynamic language made specifically for the JVM.

Groovy was designed with the JVM in mind

Groovy does not just have access to the existing Java API; its Groovy Development Kit(GDK) actually extends the Java API by adding new methods to the existing Java classes tomake them more Groovy.

Groovy is a standard governed by the Java Community Process (JCP)as Java Specification Request (JSR) 241.

如下涵盖了日常使用中常用的groovy语法,按照这个几次的使用可以很快地熟悉groovy的语法

1. 默认导入的命名空间Automatic Imports

importjava.lang.*;

importjava.util.*;

import java.net.*;

import java.io.*;

import java.math.BigInteger;

import java.math.BigDecimal;

importgroovy.lang.*;

importgroovy.util.*;

使用以上的命名空间下的接口、类等不需要引入

2. 可选分号Optional Semicolons

msg = "Hello"

msg = "Hello";

3. 可选括号Optional Parentheses

println("Hello World!")

println "Hello World!"

//Method Pointer

def pizza = new Pizza()

def deliver = pizza.&deliver()

deliver

4. 可选返回值Optional Return Statements

String getFullName(){

return "${firstName} ${lastName}"

}

//equivalent code

String getFullName(){

"${firstName} ${lastName}"

}

5. 可选类型声明Optional Datatype Declaration (Duck Typing)

s = "hello"

def s1 = "hello"

String s2 = "hello"

printlns.class

println s1.class

println s2.class

6. 可选异常处理Optional Exception Handling

//in Java:

try{

Reader reader = new FileReader("/foo.txt")

}

catch(FileNotFoundException e){

e.printStackTrace()

}

//in Groovy:

def reader = new FileReader("/foo.txt")

7. 操作符重载Operator Overloading

Operator Method

a == b or a != b a.equals(b)

a + b a.plus(b)

a - b a.minus(b)

a * b a.multiply(b)

a / b a.div(b)

a % b a.mod(b)

a++ or ++a a.next()

a- - or - -a a.previous()

a & b a.and(b)

a | b a.or(b)

a[b] a.getAt(b)

a[b] = c a.putAt(b,c)

a << b a.leftShift(b)

a >> b a.rightShift(b)

a < b or a > b or a <= b or a >= b a.compareTo(b)

8. Safe Dereferencing (?)

s = [1, 2]

println s?.size()

s = null

println s?.size()

println person?.address?.phoneNumber //可连用不用检查空

9. 自动装箱Autoboxing

autoboxes everything on the fly

float f = (float) 2.2F

f.class

primitive类型自动装箱

10. 真值Groovy Truth

//true

if(1) // any non-zero value is true

if(-1)

if(!null) // any non-null value is true

if("John") // any non-empty string is true

Map family = [dad:"John", mom:"Jane"]

if(family) // true since the map is populated

String[] sa = new String[1]

if(sa) // true since the array length is greater than 0

StringBuffersb = new StringBuffer()

sb.append("Hi")

if(sb) // true since the StringBuffer is populated

//false

if(0) // zero is false

if(null) // null is false

if("") // empty strings are false

Map family = [:]

if(family) // false since the map is empty

String[] sa = new String[0]

if(sa) // false since the array is zero length

StringBuffersb = new StringBuffer()

if(sb) // false since the StringBuffer is empty

11. Embedded Quotes

def s1 = 'My name is "Jane"'

def s2 = "My name is 'Jane'"

def s3 = "My name is \"Jane\""

单双引号都可以表示字符串

12. Heredocs (Triple Quotes)

s ='''This is

demo'''

println s

三个单、双引号

13. GStrings

def name = "John"

println "Hello ${name}. Today is ${new Date()}"

14. List/Map Shortcuts

def languages = ["Java", "Groovy", "JRuby"]

printlnlanguages.class

def array = ["Java", "Groovy", "JRuby"] as String[]

def set = ["Java", "Groovy", "JRuby"] as Set

def empty = []

printlnempty.size()

languages << "Jython"

println languages[1]

printlnlanguages.getAt(1)

languages.each{println it}

languages.each{lang ->

printlnlang

}

languages.eachWithIndex{lang, i ->

println "${i}: ${lang}"

}

languages.sort()

languages.pop()

languages.findAll{ it.startsWith("G") }

languages.collect{ it += " is cool"}

//Spread Operator (*)

println languages*.toUpperCase()

def family = [dad:"John", mom:"Jane"]

family.get("dad")

printlnfamily.dad

family.each{k,v ->

println "${v} is the ${k}"

}

family.keySet()

import groovy.sql.Sql

//Spread Operator (*)

defparams = []

params<< "jdbc:mysql://localhost:3306/test"

params<< "root"

params<< ""

params<< "com.mysql.jdbc.Driver"

printlnparams

defsql = Sql.newInstance(*params)

//defdb = [url:'jdbc:hsqldb:mem:testDB', user:'sa', password:'', driver:'org.hsqldb.jdbcDriver']

//defsql = Sql.newInstance(db.url, db.user, db.password, db.driver)

defsql = groovy.sql.Sql.newInstance('jdbc:mysql://localhost:3306/tekdays', "root", '', 'com.mysql.jdbc.Driver')

printlnsql.connection.catalog

mysql-connector-java-5.0.7-bin.jar放到groovy安装lib目录下

15. Ranges

def r = 1..3

(1..3).each{println "Bye"}

def today = new Date()

defnextWeek = today + 7

(today..nextWeek).each{println it}

16. Closures and Blocks

def hi = { println "Hi"}

hi()

def hello = { println "Hi ${it}" }

hello("John")

defcalculateTax = { taxRate, amount ->

return amount + (taxRate * amount)

}

println "Total cost: ${calculateTax(0.055, 100)}"

//预绑定

defcalculateTax = { taxRate, amount ->

return amount + (taxRate * amount)

}

def tax = calculateTax.curry(0.1)

[10,20,30].each{

println "Total cost: ${tax(it)}"

}

篇幅有些长,不过有了这些知识对深入的groovy grails的使用很有裨益。

相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
7月前
|
存储 缓存 Java
Java基础知识第二讲:Java开发手册/JVM/集合框架/异常体系/Java反射/语法知识/Java IO
Java基础知识第二讲:Java开发手册/JVM/集合框架/异常体系/Java反射/语法知识/Java IO
170 0
Java基础知识第二讲:Java开发手册/JVM/集合框架/异常体系/Java反射/语法知识/Java IO
|
存储 算法 前端开发
JVM - 基础知识
有两种方法,分别为:引用计数法和可达性分析法
109 0
|
存储 Java 编译器
JVM 基础知识
JVM 基础知识
108 0
JVM 基础知识
|
缓存 前端开发 Java
|
Java Shell
基于JVM的动态语言Groovy MetaProgramming 知识集
Metaprogramming 使groovy动态语言的特性发挥的淋漓尽致(Metaprogramming is writing code that has the ability to dynamicallychange its behavior at runtime.
858 0
|
13天前
|
Java
JVM之本地内存以及元空间,直接内存的详细解析
JVM之本地内存以及元空间,直接内存的详细解析
26 0
|
6天前
|
存储 Java
深入理解Java虚拟机:JVM内存模型
【4月更文挑战第30天】本文将详细解析Java虚拟机(JVM)的内存模型,包括堆、栈、方法区等部分,并探讨它们在Java程序运行过程中的作用。通过对JVM内存模型的深入理解,可以帮助我们更好地编写高效的Java代码,避免内存溢出等问题。
|
2月前
|
缓存 算法 安全
【JVM故障问题排查心得】「Java技术体系方向」Java虚拟机内存优化之虚拟机参数调优原理介绍(二)
【JVM故障问题排查心得】「Java技术体系方向」Java虚拟机内存优化之虚拟机参数调优原理介绍
18 0
|
6天前
|
存储 机器学习/深度学习 Java
【Java探索之旅】数组使用 初探JVM内存布局
【Java探索之旅】数组使用 初探JVM内存布局
17 0