问题
I have a groovy script called Foo.groovy
, an instance of that script can be constructed using the following syntax:
def foo = new Foo()
i know if Foo.groovy
looks like:
import groovy.transform.Field
@Field def bar
def someMethod() {
//...
}
the following syntax:
def foo = new Foo(bar: 'baz')
will use some default constructor and actually set the bar
field to baz
,
but let's say that i wanted to manipulate the passed value of bar
to add an
exclamation point at the end like so "${bar}!"
would like to be able to do something like the following (which doesn't work AFAIK):
import groovy.transform.Field
@Field def bar
Foo(args) {
bar = "${args.bar}!"
}
def someMethod() {
//...
}
Is there an idiomatic way to accomplish that in groovy?
回答1:
You may use setter method
(Foo.groovy):
import groovy.transform.Field
@Field def bar
void setBar(def bar){
this.bar = "${bar}!"
println "Setter is executed. ${bar} -> ${this.bar}"
}
And if the calling party will look like
import Foo
def foo = new Foo(bar: 'baz')
println foo.bar
the following result appears:
Setter is executed. baz -> baz!
baz!
回答2:
Any free variable in the main body of the script can be satisfied out of the Binding object. It works pretty much like a map because it has a map-based constructor and has overloaded getProperty and setProperty. http://docs.groovy-lang.org/latest/html/gapi/groovy/lang/Binding.html
Main script:
def binding = new Binding(bar: 'baz')
def foo = new Foo(binding)
foo.run()
Foo.groovy:
someMethod(bar + '!')
def someMethod(baz) { // bar/baz value must be passed in
// do something with baz
}
I have not tried this out, but it should be easy enough to plug it into Groovy Console and see what happens.
来源:https://stackoverflow.com/questions/54831615/is-there-a-way-to-specify-a-constructor-for-a-groovy-script