【问题标题】:Groovy: Constructor hash collisionGroovy:构造函数哈希冲突
【发布时间】:2018-08-09 19:22:48
【问题描述】:

我有以下 groovy 代码:

def    script
String credentials_id
String repository_path
String relative_directory
String repository_url

CredentialsWrapper(script, credentials_id, repository_name, repository_group, relative_directory=null) {
    this(script, credentials_id, 'git@gitlab.foo.com:' + repository_group +'/' + repository_name + '.git', relative_directory);             
}

CredentialsWrapper(script, credentials_id, repository_url, relative_directory=null) {

    this.script         = script;
    this.credentials_id = credentials_id;
    this.repository_url = repository_url;

    if (null == relative_directory) {

        int lastSeparatorIndex  = repository_url.lastIndexOf("/");
        int indexOfExt          = repository_url.indexOf(".git"); 
        this.relative_directory = repository_url.substring(lastSeparatorIndex+1, indexOfExt);
    }
}

Jenkins 给了我以下信息:

由于构造函数 @ 第 30 行第 7 列中的哈希冲突,无法编译 com.foo.CredentialsWrapper 类。

我不明白为什么,构造函数不同,它们的参数数量不同。

另外,“script”是“WorkflowScript”的一个实例,但我不知道我应该导入什么来访问这个类,这将允许我显式声明脚本而不是使用“def”

有什么想法吗?

【问题讨论】:

    标签: groovy hash constructor collision


    【解决方案1】:

    当你调用带有四个参数的构造函数时,你想调用第一个还是第二个?

    如果你用默认值编写构造函数/方法,groovy 实际上会生成两个或多个版本。 所以

    Test(String x, String y ="test")
    

    将导致

    Test(String x, String y) {...}
    

    Test(String x) {new Test(x, "test")}
    

    所以你的代码想编译成 4 个构造函数,但它包含带有签名的构造函数 CredentialsWrapper(def, def, def, def) 两次。 如果我正确理解您的代码,您可以省略=null 中的一个或两个。结果将是相同的,但您只会得到两个或三个签名。然后,您可以通过使用正确的参数计数调用它们来在两个版本之间进行选择。

    【讨论】:

    • 感谢您的解释。我终于制作了两个不需要默认值的构造函数,并且它正在工作。如果您对此有答案,则附加问题:当我从构造函数调用方法时,groovy 失败且没有错误并且返回的对象为空(尝试使用该对象时脚本失败)。你知道为什么吗?
    • 很高兴我能帮上忙。不幸的是,我不再使用 Jenkins,也没有在 Jenkins 中使用 Groovy 的经验。我会尝试通过添加日志消息或打印行来缩小范围。
    • 这就是我所做的,构造函数一直执行,直到找到方法,然后它就停止了。我知道这些方法工作正常,它们不需要完全构建的项目或在节点内工作。我可能会尝试做一个简单的例子并发布另一个线程。谢谢
    • 您描述的问题可能与您使用的字符串操作方法有关,这可能会导致 Pipeline 出现问题,有时需要放在 NonCPS 方法中。另一方面,afaik 构造函数通常总是 NonCPS。不过,您可以针对构造函数调用问题打开一个单独的问题。
    猜你喜欢
    • 2011-02-27
    • 2019-03-25
    • 1970-01-01
    • 2019-03-17
    • 1970-01-01
    • 2014-10-02
    • 2016-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多