views:

150

answers:

1

In a script a method receives a parameter of type File, and sends it to the constructor of File. This blows up because File doesn't have a constructor that takes another file as a parameter.

How can I intercept this call, and modify the parameter to parameter.absolutePath ?

For example :


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)
}

If that can't be done, how could I add this constructor :


File(File other) {
  this(other.absolutePath)
}
+4  A: 

I managed to find the answer here. Here's the code that makes what I wrote above work :


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