问题
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?
- 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
- 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