简体   繁体   English

测试空的凹槽闭合?

[英]testing for empty groovy closure?

I want to let users supply a groovy class with a property that is a file-selector closure which I pass on to AntBuilder's 'copy' task: 我想让用户为groovy类提供一个属性,该属性是一个文件选择器闭包,我将其传递给AntBuilder的“复制”任务:

  class Foo {
    def ANT = { fileset(dir:'/tmp/tmp1') }
  }

in my code, I pick up the ANT property as 'fAnt' and pass to Ant: 在我的代码中,我将ANT属性选择为“ fAnt”并传递给Ant:

  ant.copy(todir:'/tmp/tmp2', fAnt)

This works - but, if the user passes in an empty closure (def ANT={}) or with a selector that doesn't select anything (maybe the fileset dir doesn't exist) then it blows up. 这行得通-但是,如果用户传入一个空的闭包(def ANT = {})或使用一个没有选择任何内容的选择器(也许文件集目录不存在),则它会崩溃。 I tried surrounding the ant copy with a try-catch to catch the InvokerInvocationException, but somehow the exception comes through anyway ... while I'm tracking that down, is there a way to read back a groovy Closure's contents as a string, or to test if it's empty? 我尝试用try-catch包围ant副本以捕获InvokerInvocationException,但是无论如何还是会发生异常……当我跟踪该异常时,是否有办法以字符串的形式回读Groovy Closure的内容,或者测试是否为空?

In short: No. You can't decompile a closure in a meanngful way at runtime. 简而言之:不能。您无法在运行时以一种笨拙的方式反编译闭包。 If it's user supplied, the Closure could even be a Java class. 如果由用户提供,则Closure甚至可以是Java类。

Long answer: If you want to do a lot of work, you might be able to, but it's probably not worth it. 长答案:如果您想做很多工作,也许可以,但是这不值得。 The Groovy parser is part of the API, so if you have access to the source, you can theoretically examine the AST and determine if the closure is empty. Groovy解析器是API的一部分,因此,如果您有权访问源,则可以从理论上检查AST并确定闭包是否为空。 Look into the SourceUnit class. 查看SourceUnit类。

It's almost certainly not worth the effort though. 但是,几乎可以肯定,这是不值得的。 You're better off catching the exception and adding a helpful message like "You may have passed an empty closure or invalid fileset". 最好捕获异常并添加一条有用的消息,例如“您可能已经传递了空的闭包或无效的文件集”。

一个谜团解决了-我需要捕获的异常是org.apache.tools.ant.BuildException-因此我可以捕获该异常以捕获错误,但原始问题仍然存在-有没有办法检查Closure的内容?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM