Unmi 学习 Groovy 之闭包与资源、异常处理

闭包还为我们提供了改善处理复杂 try/catch/finally 结构的方法。利用闭包,很容易编写正确处理资源和异常的代码。使用闭包的新方法已经添加到处理文件、进程和数据库连接的标准 Java 类中。当它们用在 Groovy 中的时候,不必处理和担心资源的关闭。首先我们来看看 Groovy 实现这一方式的原理。我们假设有这么一个资源处理类。

 1class Resource{
 2    public Resource(String resourceName) throws ResourceException{
 3        //open the resource
 4    }
 5
 6    public Object read() throws ResourceException{
 7        //return data or false as the end marker
 8    }
 9
10    public void close() throws ResourceException{
11        //close the resource
12    }
13}

那么我们的打开、读取和关闭资源的典型的 Java 代码看起来就像这样:

 1Resource res = new Resource("someName");
 2try{
 3    while(result=res.read()){
 4        println(result);
 5    }
 6}catch(ResourceException e){
 7    e.printStackTrace();
 8}finally{
 9    try{
10        res.close();
11    }catch(ResourceException e){
12    }
13}

这在数据库的操作是很常见的代码,当然我们一般不会处处这么写的,而是会写一个工具类方法来统一处理这种异常,不过这种办法仍显笨拙。

而 Groovy 的闭包能使得我们轻松优雅的处理资源,只要在原始类中增加一个新的 read() 方法,这个 read() 方法接受一个 Closure 参数,完整的 Resource 类如下:

 1class Resource{
 2    public Resource(String resourceName) throws ResourceException{
 3        //open the resource
 4    }
 5
 6    public Object read() throws ResourceException{
 7        //return data or false as the end marker
 8    }
 9
10    public void read(Closure closure) throws ResourceException{
11        try{
12            while(result = read()){
13                closure.call(result);
14            }
15        }catch(ResourceException){
16            throw e;
17        }finally{
18            try{
19                close()
20            }catch(ResourceException e){
21            }
22        }
23    }
24
25    public void close() throws ResourceException{
26        //close the resource
27    }
28}

OK,现在有了这个 read(Closure closure) 方法后,您使用上面的资源就简单多了,只要写成

1new Resource("someName").read{
2    println it;
3}

就行啦,非常简洁。

异常处理、资源打开和关闭被移到了接受闭包参数的 read() 方法中。这是 Groovy 中一种常见的应用哲学。它使 Groovy 脚本更容易阅读,也使它们编写起来更快且更轻松。它被广泛应用于系统操作(文件和进程操作) 和数据库使用等方法,Groovy 对标准的 Java 类进行了扩展,在以后会详细介绍这方面的用法。

最后来欣赏几个 Groovy 闭包这方面用法的代码:

1//-----逐行以大写行式输出文件内容
2import java.io.File;
3lineList = new File("foo.txt").readLines();
4liineList.each {
5    println it.toUpperCase();
6}
1//-----数据库查询操作
2import groovy.sql.Sql;
3
4sql = Sql.newInstance("jdbc:mysql://localhost/groovy", "root", "", "com.mysql.jdbc.Driver");
5sql.eachRow("select * from user"){
6    println it.username;
7}

参考:1. 《Java 脚本编程 语言、框架与模式》 第 4 章

永久链接 https://yanbin.blog/unmi-study-groovy-closure-resource-exception/, 来自 隔叶黄莺 Yanbin's Blog
[版权声明] 本文采用 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 进行许可。