groovy隐式函数参数类型转换

joh*_*ith 5 groovy

假设有一个这样的方法:someAPI(Integer)。我还有课

class MyClass{

    int toInteger(){
        0 // just for demo. the value will be generated on the fly
    }


    public <T> T asType(Class<T> c){
        0 // just for demo. the value will be generated on the fly
    }
}

MyClass myClass
someAPI(myClass as Integer) // OK but it's more like groovy than DSL
someAPI(myClass) // This is what i want, but it gives me an error: method not found.
Run Code Online (Sandbox Code Playgroud)

我怎样才能让groovy自动为我投射它?当然someAPI()不是我可以修改的。

Ren*_*ato 4

someApi方法必须存在于类或接口中。假设类或接口被调用MyOtherClass,那么你可以这样做:

class MyOtherClass {
    void someAPI(Integer i) {println "I is $i"}
}

MyOtherClass.metaClass.someAPI = { i ->
    delegate.someAPI(i as Integer)
}


class MyClass {
    int toInteger() { 22 }
    def asType(Class c) { 22 }
}
Run Code Online (Sandbox Code Playgroud)

现在,这有效:

// this prints "I is 52" as expected because Strings can be cast to Integers
new MyOtherClass().someAPI("52")

// prints "I is 22", which is what MyClass returns when cast to Integer
new MyOtherClass().someAPI(new MyClass())

// Integers will work as expected, prints "I is 77"
new MyOtherClass().someAPI(77)
Run Code Online (Sandbox Code Playgroud)

我所做的是路径类型的元类,该类型拥有someAPI我想要接受任何内容的方法...请注意,我向someAPI其中添加了一个新的参数,它采用非类型化参数...

someAPI我通过在将参数转换为 后委托给实际实现来实现新版本Integer,这就是您想要做的。

当然,这只适用于 Groovy 代码。