有没有一种方法可以为Groovy脚本指定构造函数? [英] is there a way to specify a constructor for a groovy script?
问题描述
我有一个名为 Foo.groovy
的groovy脚本,可以使用以下语法构造该脚本的实例:
I have a groovy script called Foo.groovy
, an instance of that script can be constructed using the following syntax:
def foo = new Foo()
我知道 Foo.groovy
是否看起来像:
import groovy.transform.Field
@Field def bar
def someMethod() {
//...
}
以下语法:
def foo = new Foo(bar: 'baz')
将使用一些默认的构造函数,并将 bar
字段实际设置为 baz
,但是,假设我想操纵 bar
的传递值来添加一个像这样"$ {bar}!"
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}!"
希望能够执行以下操作(不适用于AFAIK):
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?
推荐答案
您可以使用setter方法
You may use setter method
(Foo.groovy):
(Foo.groovy):
import groovy.transform.Field
@Field def bar
void setBar(def bar){
this.bar = "${bar}!"
println "Setter is executed. ${bar} -> ${this.bar}"
}
如果主叫方看起来像
import Foo
def foo = new Foo(bar: 'baz')
println foo.bar
出现以下结果:
Setter is executed. baz -> baz!
baz!
这篇关于有没有一种方法可以为Groovy脚本指定构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!