Problems with GroovyShell and propertyMissing()
I'm having problems using propertyMissing()
together with GroovyShell
I have the files
/**
* @file FooScript.groovy
*/
abstract class FooScript extends Script {
def propertyMissing(String name) {
"This is the pr开发者_如何学Pythonoperty '$name'"
}
def propertyMissing(String name, value) {
println "You tried to set property '$name' to '$value'"
}
}
and
/**
* @file FooScriptTest.groovy
*/
import org.codehaus.groovy.control.*
def fooScript = """\
foo = 'bar'
println foo"""
def conf = new CompilerConfiguration()
conf.setScriptBaseClass("FooScript")
def sh = new GroovyShell(conf)
sh.evaluate fooScript
When I run FooScriptTest.groovy
I expect the output
You tried to set property 'foo' to 'bar'
This is the property 'foo'
What I get is:
bar
Seems my propertyMissing()
is overridden by the default one. How do I prevent this?
use this instead
abstract class BarScript extends Script {
def getProperty(String name) {
"This is the property '$name'"
}
void setProperty(String name, value) {
println "You tried to set property '$name' to '$value'"
}
}
missingProperty
methods are the last resource to catch a property access,
tested only when everything else has failed.
but groovy.lang.Script
already implements the higher priority methods get/setProperty
.
so to catch a missing property, these are the methods you have to override in your subclass
精彩评论