How can I intercept this constructor call in Groovy?
-
12-09-2019 - |
Question
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)
}
Solution
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)
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow