设置参数的默认值会产生重载方法,并且从左到右组合,因此很难制作method(12)
并且还能够传递地图条目。
你的方法def method(paramMap, specificVar1=7, specificVar2=14)
将生成以下方法:
Object Maps.method(java.lang.Object)
Object Maps.method(java.lang.Object,java.lang.Object)
Object Maps.method(java.lang.Object,java.lang.Object,java.lang.Object)
以及带有地图参数的完全类型化方法:
def method3(Map paramMap=[:], Integer specificVar1=7, Integer specificVar2=14) {
}
会生成以下方法:
Object Maps.method3()
Object Maps.method3(java.util.Map)
Object Maps.method3(java.util.Map,java.lang.Integer)
Object Maps.method3(java.util.Map,java.lang.Integer,java.lang.Integer)
(没有合适的方法method(12)
).
此外,传递给该方法的条目将被收集并插入到第一个map范围。方法如下:
def method4(Integer specificVar1=7, Integer specificVar2=14, Map map=[:]) {
生成:
Object Maps.method4()
Object Maps.method4(java.lang.Integer)
Object Maps.method4(java.lang.Integer,java.lang.Integer)
Object Maps.method4(java.lang.Integer,java.lang.Integer,java.util.Map)
Thus, method4 12, a:'b'
失败并显示:
No signature of method: Maps.method4() is applicable for argument types:
(java.util.LinkedHashMap, java.lang.Integer) values: [[a:b], 12]
所以,不,我认为你不能使用地图做你想做的事:-)。
解决方案一:
如果您需要纯动态解决方案,则可以使用单个映射参数:
def method5(Map map) {
def specificVar1 = map.specificVar1 ?: 7
def specificVar2 = map.specificVar2 ?: 14
}
解决方案2(已更新):
您可以创建一个类来表示参数。使用映射强制到对象中是可静态编译的,并且是它的语法糖。
@groovy.transform.CompileStatic
class Maps {
def method6(Foo foo) { "$foo.params, $foo.specificVar1, $foo.specificVar2" }
def method6(Map map) { method6 map as Foo }
static main(args) {
def maps = new Maps()
assert maps.method6(params: [a: 'b', c: 'd'], specificVar1: 40) ==
"[a:b, c:d], 40, 14"
assert maps.method6(new Foo(params: [a: 'b', c: 'd'], specificVar2: 21)) ==
"[a:b, c:d], 7, 21"
}
}
class Foo {
def specificVar1 = 7, specificVar2 = 14, params = [:]
}
解决方案3:
一个重载方法。
def method6(Map paramMap, Integer specificVar1=7, Integer specificVar2=14) {
"$paramMap, $specificVar1, $specificVar2"
}
def method6(Integer specificVar1=7, Integer specificVar2=14) {
method6 [:], specificVar1, specificVar2
}
assert method6( 12 ) == "[:], 12, 14"
assert method6( ) == "[:], 7, 14"
assert method6( a:'b', 18 ) == "[a:b], 18, 14"
assert method6( 18, a:'b', 27 ) == "[a:b], 18, 27"
assert method6( 90, 100 ) == "[:], 90, 100"
assert method6( a:'b', 140, c:'d' ) == "[a:b, c:d], 140, 14"
地图版本方法不能有默认参数,否则两个方法都会生成无参数method6
这些都会发生冲突。