测试空凹槽闭合?
我想让用户提供一个带有文件选择器闭包属性的 groovy 类,我将其传递给 AntBuilder 的“复制”任务:
class Foo {
def ANT = { fileset(dir:'/tmp/tmp1') }
}
在我的代码中,我选择 ANT 属性作为“fAnt”并传递给 Ant
ant.copy(todir:'/tmp/tmp2', fAnt)
:有效 - 但是,如果用户传入一个空闭包(def ANT={})或使用不选择任何内容的选择器(可能文件集目录不存在),那么它就会爆炸。我尝试用 try-catch 围绕 ant 副本来捕获 InvokerInvocationException,但无论如何,异常都会出现......当我跟踪它时,有没有办法以字符串形式读回 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:
class Foo {
def ANT = { fileset(dir:'/tmp/tmp1') }
}
in my code, I pick up the ANT property as 'fAnt' and pass to 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. 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
简而言之:不。您无法在运行时以有意义的方式反编译闭包。如果它是用户提供的,那么 Closure 甚至可以是一个 Java 类。
长答案:如果您想做很多工作,也许可以,但这可能不值得。 Groovy 解析器是 API 的一部分,因此如果您有权访问源代码,理论上您可以检查 AST 并确定闭包是否为空。查看 SourceUnit 类。
但这几乎肯定不值得付出努力。您最好捕获异常并添加有用的消息,例如“您可能传递了空闭包或无效文件集”。
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.
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. Look into the SourceUnit class.
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 - 所以我可以捕获它来捕获错误,但最初的问题仍然存在 - 有没有办法检查闭包的内容?
One mystery solved - the exception I need to catch is org.apache.tools.ant.BuildException - so I can just catch that to trap errors, but the original question remains - is there a way to examine a Closure's contents?