How can I intercept this constructor call in Groovy?
Asked Answered
P

1

6

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)
}
Pigweed answered 10/8, 2009 at 12:57 Comment(0)
P
7

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)
}
Pigweed answered 10/8, 2009 at 13:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.