groovy - 如何优雅地处理 groovy 模糊方法重载

标签 groovy

我知道有类似的问题,但答案并不令人满意。

当调用以 null 作为参数的方法时,我收到 Groovy 模糊方法重载错误。

例如:

class A{
    sampleMethod (B bObj){
        if(bObj == null) {
            handleNullArgumentGracefully()
        }
        ... do some cool stuff ...
    }

    sampleMethod (C cObj){
        ... do some other cool stuff ...
    }
}

现在,当我调用 sampleMethod(null) 时,groovy 不知道应该调用哪个方法。这很清楚但是是否可以将这两种方法中的一种设置为默认方法来处理此类空调用?我想在被调用者端处理这个问题,而调用者端处理这个问题(我不想在调用者端转换一些东西)

更新: 我找到了一个解决方案,但我不知道为什么:将非默认方法转换为闭包属性

class app {
    static void main(String[] args) {
        def a = new A()
        a.sampleMethod(new B())
        a.sampleMethod(new C())
        a.sampleMethod(null)
    }
}

class A {
    def sampleMethod(B bObj = null) {
        if (bObj == null) {
            println("handle null")
        }
        println("1")
    }

    def sampleMethod = { C cObj ->
        println("2")
    }
}

class B {

}

class C {

}

最佳答案

以下操作将失败,并出现方法 A#sampleMethod 的模糊方法重载

class A{
    def sampleMethod (Number o=null){
        println "num $o"
    }

    def sampleMethod (String o){
        println "str $o"
    }
}

new A().sampleMethod(null)

这个可以工作(对象将被调用为空):

class A{
    def sampleMethod (Number o=null){
        println "num $o"
    }

    def sampleMethod (String o){
        println "str $o"
    }

    def sampleMethod(Object o){
        println "obj $o"
    }
}

new A().sampleMethod(null)

但我喜欢这个:

class A{
    def _sampleMethod (Number o){
        println "num $o"
    }

    def _sampleMethod (String o){
        println "str $o"
    }

    def sampleMethod(Object o){
        if(o==null){
            println "null"
            return null
        }else if(o instanceof Number){
            return _sampleMethod ((Number) o)
        }else if(o instanceof String){
            return _sampleMethod ((String) o)
        }
        throw new IllegalArgumentException("wrong argument type: ${o.getClass()}")
    }
}

new A().sampleMethod(null)

关于groovy - 如何优雅地处理 groovy 模糊方法重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44453762/

相关文章:

java - 可以从 Groovy 代码中使用 Scala Breeze 库吗?

unit-testing - 如何在 Grails 单元测试中模拟 Java 类?

java - grails urlMappings dsl

Groovy 字符串解析成组

常规列表传播

android - Groovy调用adb命令来提取文件,但是新文件不可见

security - Grails:加密查询参数,使用散列加密/解密 url 和隐藏字段中的参数

Python 和 Groovy 函数选项

groovy - Gradle插件的默认属性

jenkins - 在Jenkinsfile中的哪里放置try/catch