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

简介: 在使用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的使用很有裨益。

相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
相关文章
|
存储 缓存 Java
Java基础知识第二讲:Java开发手册/JVM/集合框架/异常体系/Java反射/语法知识/Java IO
Java基础知识第二讲:Java开发手册/JVM/集合框架/异常体系/Java反射/语法知识/Java IO
552 0
Java基础知识第二讲:Java开发手册/JVM/集合框架/异常体系/Java反射/语法知识/Java IO
|
存储 算法 前端开发
JVM - 基础知识
有两种方法,分别为:引用计数法和可达性分析法
318 0
|
存储 Java 编译器
JVM 基础知识
JVM 基础知识
257 0
JVM 基础知识
|
缓存 前端开发 Java
|
Java Shell
基于JVM的动态语言Groovy MetaProgramming 知识集
Metaprogramming 使groovy动态语言的特性发挥的淋漓尽致(Metaprogramming is writing code that has the ability to dynamicallychange its behavior at runtime.
992 0
|
Arthas 存储 算法
深入理解JVM,包含字节码文件,内存结构,垃圾回收,类的声明周期,类加载器
JVM全称是Java Virtual Machine-Java虚拟机JVM作用:本质上是一个运行在计算机上的程序,职责是运行Java字节码文件,编译为机器码交由计算机运行类的生命周期概述:类的生命周期描述了一个类加载,使用,卸载的整个过类的生命周期阶段:类的声明周期主要分为五个阶段:加载->连接->初始化->使用->卸载,其中连接中分为三个小阶段验证->准备->解析类加载器的定义:JVM提供类加载器给Java程序去获取类和接口字节码数据类加载器的作用:类加载器接受字节码文件。
1067 55
|
Arthas 监控 Java
Arthas memory(查看 JVM 内存信息)
Arthas memory(查看 JVM 内存信息)
1059 6
|
9月前
|
存储 缓存 Java
我们来说一说 JVM 的内存模型
我是小假 期待与你的下一次相遇 ~
582 5
|
9月前
|
存储 缓存 算法
深入理解JVM《JVM内存区域详解 - 世界的基石》
Java代码从编译到执行需经javac编译为.class字节码,再由JVM加载运行。JVM内存分为线程私有(程序计数器、虚拟机栈、本地方法栈)和线程共享(堆、方法区)区域,其中堆是GC主战场,方法区在JDK 8+演变为使用本地内存的元空间,直接内存则用于提升NIO性能,但可能引发OOM。