2009-08-10 59 views
6

在脚本中,一个方法接收File类型的参数,并将其发送给File的构造函数。由于File没有一个将另一个文件作为参数的构造函数,因此这种情况就暴发了。如何拦截Groovy中的此构造函数调用?

如何拦截此调用并将参数修改为parameter.absolutePath

例如:


def x = new File("some_file") 
... 
def meth(def param) { 
    def y = new File(param) // if param is of type File, this blows up 
    // and I'd like groovy's intercepting capabilities to invoke this instead 
    // def y = new File(param.absolutePath) 
} 

如果不能做到,我怎么可以添加此构造:


File(File other) { 
    this(other.absolutePath) 
} 

回答

6

我设法找到了答案here。这里的代码,使我在上面写的工作:


File.metaClass.constructor << { File arg -> 
    new File(arg.absolutePath) 
}