Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I intercept this constructor call in Groovy?

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)
}
like image 703
Geo Avatar asked Aug 10 '09 12:08

Geo


1 Answers

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)
}
like image 133
Geo Avatar answered Oct 17 '22 03:10

Geo