且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Groovy:从类内部方法动态添加Groovy类的属性

更新时间:2023-12-05 15:44:46

You can make your class extend Expando (Expando is described here)

class MyClass extends Expando {
    def myMethod() {
        variable = "I am a variable"
    }

    def propertyMissing(String name) {
        println "Missing property $name"
    }
}

MyClass myClass = new MyClass()
myClass.myProperty
myClass.myMethod()
println myClass.variable

You can hand-roll a similar functionality by creating your own backing map for variables, and writing the get/setProperty methods yourself, ie:

class MyClass {

    def myMethod() {
        variable = "I am a variable"
    }

    def propertyMissing(String name) {
        println "Missing property $name"
    }

    def backingMap = [:]

    Object getProperty( String property ) {
      if( backingMap[ property ] == null ) {
        propertyMissing( property )
      }
      else {
        backingMap[ property ]
      }
    }

    void setProperty( String property, Object value ) {
      backingMap[ property ] = value
    }
}

MyClass myClass = new MyClass()
myClass.myProperty
myClass.myMethod()
println myClass.variable

Though as you can see from the source code for Expando, this hand-rolled version does a lot less checks and I'd trust it less ;-)

相关阅读

推荐文章