Groovy元编程(getProperty)仅在从类外部调用时工作?
我用Groovy尝试了一些(运行时)元编程。我接着实现了GroovyInterceptable的getProperty方法。但现在我发现,这只在从外部获取对象的属性时有效。从该类中的方法内部获取属性时,不会调用我的getProperty方法(请参见下面的代码示例) 现在,这是意料之中的事吗?一直都是这样吗?一位同事告诉我,过去这与他记忆中的情况不同。从内部和外部读取属性是否有另一种方法调用我的getProperty方法Groovy元编程(getProperty)仅在从类外部调用时工作?,groovy,metaprogramming,Groovy,Metaprogramming,我用Groovy尝试了一些(运行时)元编程。我接着实现了GroovyInterceptable的getProperty方法。但现在我发现,这只在从外部获取对象的属性时有效。从该类中的方法内部获取属性时,不会调用我的getProperty方法(请参见下面的代码示例) 现在,这是意料之中的事吗?一直都是这样吗?一位同事告诉我,过去这与他记忆中的情况不同。从内部和外部读取属性是否有另一种方法调用我的getProperty方法 class SomeGroovyClass implements Groov
class SomeGroovyClass implements GroovyInterceptable {
def foo
SomeGroovyClass() {
foo = "ctor"
}
def getProperty(String name) {
if (name == "foo") {
return "blub"
} else {
return "foo"
}
}
def test2() {
System.out.println "foo from inside via method call: " + this.foo
}
}
def someGroovyClass = new SomeGroovyClass()
System.out.println "foo from outside: " + someGroovyClass.foo
someGroovyClass.test2()
输出为
foo from outside: blub
foo from inside via method call: ctor
强制使用getProperty方法的一种方法是强制用于访问
this
的类型。将test2
方法更改为:
def test2() {
println "foo from inside via method call: " + ((GroovyInterceptable) this).foo
}
结果:
~> groovy solution.groovy
foo from outside: blub
foo from inside via method call: blub
强制类型的替代方法:
def test2() {
def me = this as GroovyInterceptable
println "foo from inside via method call: " + me.foo
}
及
我可以摸索groovy编译器的来源……它真的无法知道您要查找的foo
属性的哪个处理,除非您明确说明它
我相信getProperty
机制的主要目的是覆盖对不存在的属性的访问。在我看来,当一个属性可用时,默认使用现有属性是一个合理的选择,并且它们仍然保持打开的状态,因为您总是可以使用如上所述的类型化访问强制执行操作
def test2() {
GroovyInterceptable me = this
println "foo from inside via method call: " + me.foo
}