更新时间:2023-12-05 15:44:46
You can make your class extend Expando
(Expando is described here)
class MyClass extends Expando {
def myMethod() {
variable = "I am a variable"
}
def propertyMissing(String name) {
println "Missing property $name"
}
}
MyClass myClass = new MyClass()
myClass.myProperty
myClass.myMethod()
println myClass.variable
You can hand-roll a similar functionality by creating your own backing map for variables, and writing the get/setProperty
methods yourself, ie:
class MyClass {
def myMethod() {
variable = "I am a variable"
}
def propertyMissing(String name) {
println "Missing property $name"
}
def backingMap = [:]
Object getProperty( String property ) {
if( backingMap[ property ] == null ) {
propertyMissing( property )
}
else {
backingMap[ property ]
}
}
void setProperty( String property, Object value ) {
backingMap[ property ] = value
}
}
MyClass myClass = new MyClass()
myClass.myProperty
myClass.myMethod()
println myClass.variable
Though as you can see from the source code for Expando, this hand-rolled version does a lot less checks and I'd trust it less ;-)