如何使用GroovyScript和Jenkins导入类?

时间:2019-06-19 19:26:24

标签: jenkins groovy

我在常规文件中有以下内容...

// jenkins/Application.groovy
package jenkins

class Application{
    String name
    Application(name){
        this.name = name
    }
}

我正在尝试导入它,并且已经尝试了这些,但是似乎都没有用。这些都在jenkins / Test.groovy

final GroovyScriptEngineImpl engine = (GroovyScriptEngineImpl) this.scriptingEngines.getEngineByName("groovy");
GroovyClassLoader classLoader = engine.getClassLoader();
classLoader.parseClass(new GroovyCodeSource("./jenkins/Application.groovy"))
engine.setClassLoader(classLoader)

这给了。

  

Script1.groovy:17:无法解析类Application

然后我尝试了...

// jenkins/Application.groovy
// Added
return { Application }
// jenkins/Test.groovy
app = load "./jenkins/Application.groovy"

def dna = new app.Application("blah")

然后我得到...

  

Script1.groovy:11:无法解析类app.Application

如何在Jenkins GroovyScript中导入呼叫?

更新

我将代码更改为以下代码(并移至域文件夹中)...

app = load "./jenkins/domain/Application.groovy"
def dna = app.newInstance([name:"blah"] as Object[])

我跑步时得到...

  

org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException:不允许脚本使用staticMethod org.codehaus.groovy.runtime.DefaultGroovyMethods newInstance java.lang.Class java.lang.Object []

1 个答案:

答案 0 :(得分:1)

想法

您可以从加载的脚本中返回-类(不是实例)

然后创建新实例,您可以调用class.newInstance( Object [] argList )

http://docs.groovy-lang.org/latest/html/groovy-jdk/java/lang/Class.html#newInstance(java.lang.Object[])

因此,从理论上讲这应该可行:

./ jenkins / Application.groovy


class Application{
    String name
    Application(name){
        this.name = name
    }
}

return Application.class

管道:

def app = load "./jenkins/Application.groovy"
def dna = app.newInstance( "blah" )