[英]How can you change the default Closure resolve strategy for a Groovy script?
[英]groovy with ambiguous closure: How to resolve
我試圖在groovy中這樣做
def results = new File(someDirectory).listFiles { it.name.startsWith 'foo'}
但是,我得到了可以理解的錯誤:
groovy.lang.GroovyRuntimeException: Ambiguous method overloading for method java.io.File#listFiles.
Cannot resolve which method to invoke for [class change$_getRollback_closure1] due to overlapping prototypes between:
[interface java.io.FileFilter]
[interface java.io.FilenameFilter]
我如何告訴它使用FileFilter ?
我最后寫了一些簡單的java風格:
File[] files = someDir.listFiles( new FileFilter(){
@Override
boolean accept(File pathname) {
return pathname.name.startsWith("foo")
}
})
您可以強制轉換或強制關閉以指定您所指的SAM類型/功能接口。
// using a typecast:
def results = new File(someDirectory).listFiles((FileFilter) { it.name.startsWith 'foo'})
// using as keyword:
def results = new File(someDirectory).listFiles({ it.name.startsWith 'foo'} as FileFilter)
// using SAM-type coercion:
FileFilter ff = { it.name.startsWith 'foo'}
def results = new File(someDirectory).listFiles(ff)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.