GroovyShell 和 propertyMissing() 的问题
我在使用 propertyMissing()
和 GroovyShell
时遇到问题
,我有这些文件
/**
* @file FooScript.groovy
*/
abstract class FooScript extends Script {
def propertyMissing(String name) {
"This is the property '$name'"
}
def propertyMissing(String name, value) {
println "You tried to set property '$name' to '$value'"
}
}
,
/**
* @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
当我运行 FooScriptTest.groovy
时,我期望输出
您尝试将属性“foo”设置为“bar”
这是属性“foo”
我得到的是:
栏
看来我的 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 property '$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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用此方法来代替
missingProperty
方法是捕获属性访问的最后一个资源,仅当其他一切都失败时才进行测试。
但 groovy.lang.Script 已经实现了更高优先级的方法 get/setProperty。
因此,要捕获丢失的属性,您必须在子类中重写这些方法
use this instead
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 methodsget/setProperty
.so to catch a missing property, these are the methods you have to override in your subclass