0

我在使用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()的被默认覆盖了。我该如何防止这种情况?

4

1 回答 1

2

改用这个

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方法是捕获属性访问的最后一个资源,只有在其他一切都失败时才进行测试。
groovy.lang.Script已经实现了更高优先级的方法get/setProperty
因此要捕获丢失的属性,这些是您必须在子类中覆盖的方法

于 2011-05-11T22:58:55.120 回答