Groovy传递LinkedHashMap至方法时出现MissingMethod错误求助
解决你的Groovy类方法调用问题
嘿,我一眼就揪出问题所在啦!你的代码里藏了个低级但致命的拼写错误,另外还有个小细节可以优化,让我慢慢给你说:
核心问题:方法名拼写错误
你在Tester类里定义的方法是exectute(注意中间多了一个t),但调用的时候却写的是testclass.execute(arg)——这就相当于你给方法起了个名字叫“张三”,却喊“李四”来干活,Groovy当然找不到对应的方法,直接抛出MissingMethodException啦!
可选优化:参数类型更灵活
Groovy是动态语言,没必要把参数类型写死成java.util.LinkedHashMap,直接用Map或者def会让代码更通用,不过这不是导致错误的原因,只是个小建议~
修正后的完整代码
class Tester { // 修正方法名拼写:exectute → execute def execute(Map tests) { println("Tests are ${tests}") } } def funct(def test) { println "Test is ${test}" } def arg = [:] arg['CASE 1'] = [ script: "test.sh", log: false ] def testclass = new Tester() println "${arg}" funct(arg) testclass.execute(arg)
运行结果
修正后执行代码,就能得到你预期的输出啦:
[CASE 1:[script:test.sh, log:false]] Test is [CASE 1:[script:test.sh, log:false]] Tests are [CASE 1:[script:test.sh, log:false]]
补充说明
如果你非要指定java.util.LinkedHashMap作为参数类型也完全没问题,只要把方法名改对就行——因为Groovy里用[:]创建的默认就是LinkedHashMap实例,参数类型是完全匹配的。
内容的提问来源于stack exchange,提问作者Hugo
相关产品推荐
相关产品推荐

