【问题标题】:Groovy metaprogramming (getProperty) only works when called from outside the class?Groovy 元编程(getProperty)仅在从类外部调用时才有效?
【发布时间】:2019-09-25 13:52:09
【问题描述】:

我尝试了一些使用 Groovy 的(运行时)元编程。我继续实现了 GroovyInterceptable 的 getProperty 方法。但是现在我发现这仅在从外部获取对象的属性时才有效。从该类的方法中获取属性时,不会调用我的 getProperty 方法(请参见下面的代码示例)。

现在,这是预期的吗?一直都是这样吗?一位同事告诉我,这在过去(与他所记得的)不同。是否有另一种方法可以让从内部和外部读取的属性都调用我的 getProperty 方法?

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

【问题讨论】:

    标签: groovy metaprogramming


    【解决方案1】:

    强制使用 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
      }
    

      def test2() {
        GroovyInterceptable me = this
        println "foo from inside via method call: " + me.foo
      }
    

    我可以了解 groovy 编译器的来源...除非您明确说明,否则它确实无法知道您正在寻找的 foo 属性的哪种处理方式。

    我相信getProperty 机制的主要目的是覆盖对不存在的属性的访问。在我看来,这使得在可用时默认使用现有属性是一个合理的选择,并且它们仍然敞开大门,因为您始终可以使用上述类型的访问来强制执行操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-16
      • 2013-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-24
      • 2019-12-31
      • 1970-01-01
      相关资源
      最近更新 更多