Geo*_*Geo 6 groovy constructor intercept
在脚本中,方法接收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)
}
Run Code Online (Sandbox Code Playgroud)
如果无法做到,我怎么能添加这个构造函数:
File(File other) {
this(other.absolutePath)
}
Run Code Online (Sandbox Code Playgroud)
我设法在这里找到答案.以下是使我上面写的内容有效的代码:
File.metaClass.constructor << { File arg ->
new File(arg.absolutePath)
}
Run Code Online (Sandbox Code Playgroud)