【问题标题】:How can I intercept this constructor call in Groovy?如何在 Groovy 中拦截此构造函数调用?
【发布时间】:2009-08-10 12:57:46
【问题描述】:

在脚本中,方法接收 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)
}

【问题讨论】:

    标签: groovy constructor intercept


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多