首页 > 解决方案 > Groovy 类工厂模式给出了奇怪的错误

问题描述

我是 groovy 的新手,我正在尝试一些 groovy 代码。我有这种情况。我有以下模块

package com.utils

abstract class Base {

    static String data = ''

}
package com.utils

class A extends Base {

    static String data = 'dummy'

}
package com.utils

class B extends Base {

    static String data = 'dummy'

}
package com.utils

class ShapeFactory {
    static Map <String,Object> shapes = [
        "a": A,
        "b": B
    ]

    static Object get_shapes(String shape) {
        return shapes.get(shape);
    }
}

And in the main file I am using

在主文件中,这里是它失败并出现奇怪错误的地方。我无法确定原因,我将不胜感激。

import com.utils.ShapeFactory

def shapeA = ShapeFactory.get_shapes('a')

shapeA.data // here it fails with the below error
hudson.remoting.ProxyException: org.codehaus.groovy.runtime.typehandling.GroovyCastException: 
Cannot cast object '[]' with class 'java.util.ArrayList' to class 'java.util.Map' 
due to: groovy.lang.GroovyRuntimeException: 
Could not find matching constructor for: java.util.Map()

任何帮助将不胜感激,谢谢

标签: groovyjenkins-groovy

解决方案


抱歉,我发现了问题,在 Base 类中,我还有一个 Map 变量,它被初始化为一个数组

abstract class Base {
   static String data = ''
   static Map mapper = []  // This has to be [:]
}

推荐阅读