如何优雅地处理时髦的模棱两可的方法重载



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

调用以 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 {
}

以下内容将失败并显示Ambiguous method overloading for method 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)

最新更新