2009-08-10 61 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) 
}