6

在脚本中,方法接收 File 类型的参数,并将其发送给 File 的构造函数。这是因为 File 没有将另一个文件作为参数的构造函数。

如何拦截此调用,并将参数修改为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)
}
4

1 回答 1

7

我设法在这里找到了答案。这是使我在上面编写的代码起作用的代码:


File.metaClass.constructor << { File arg ->
  new File(arg.absolutePath)
}
于 2009-08-10T13:18:39.217 回答