'include' of functions in groovy scripts

泪湿孤枕 提交于 2020-02-24 14:57:12

问题


I'm writing a number of scripts in groovy. And I need some kind of code reuse in my scripts. How can I do it?

  1. I can put this code in a class. But it is hardly to support solution - part of code is in the interpreted script and the other is in compiled class
  2. I can use 'evaluate', but I need reuse of a function, which has return value. I tried "evaluate" of functions definitions and it seems to be not working.

Can you recommend some approach of "include" of functions definitions in a script?

Thank you!


回答1:


There is no need to compile the groovy script, you can include a script defined as a class just fine.

Take a file SomeClass.groovy

class SomeClass {
    def add(a,b){
        return a+b
    }
}

and a script SomeScript.groovy

println(new SomeClass().add(1,1))

This will work as long as SomeClass.groovy is on the CLASSPATH.

EDITS

class SomeClass {
    def static add(a,b){
        return a+b
    }
}

Call as:

println(SomeClass.add(1,1))


来源:https://stackoverflow.com/questions/8110689/include-of-functions-in-groovy-scripts

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!