groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From OC <...@ocs.cz>
Subject static propertyMissing in an interface (was: interface/implementation patten)
Date Fri, 01 Apr 2016 01:48:05 GMT
Hello there,

playing with possibilities of the i/i pattern, I have found one can install a static property
to an interface, and then use the property all right -- see a proof-of-concept below.

Since it might be used e.g. to create instances or to get a factory through public API based
on interfaces (which would otherwise not be possible without exposing the implementation class),
this is truly interesting.

The question is: can I rely on this rather arcane behaviour, that it will not be broken in
future Groovy versions?

Thanks,
OC

===
78 /tmp> <q.groovy
class q {
  static main(av) {
    ExpandoMetaClass.enableGlobally()
    Root.metaClass.static.propertyMissing={ name ->
      String getter="get${name.capitalize()}"
      println "... PMISS($name) in $delegate, installing $getter()"
      def body={-> "<$name in $delegate>" }
      delegate.metaClass.static."$getter"=body
      delegate."$getter"() // I wonder why just "body()" does not work?!?
    }

    println "- ${Foo.staticPropertyOfInterfaceWow}"
    println "- ${Bar.itReallyWorks}"
    println "second time, they go directly without PMISS"
    println "- ${Foo.staticPropertyOfInterfaceWow}"
    println "- ${Bar.itReallyWorks}"
  }
}

interface Root {}
interface Foo extends Root {
}
interface Bar extends Foo {
}
79 /tmp> groovy q 
... PMISS(staticPropertyOfInterfaceWow) in interface Foo, installing getStaticPropertyOfInterfaceWow()
- <staticPropertyOfInterfaceWow in interface Foo>
... PMISS(itReallyWorks) in interface Bar, installing getItReallyWorks()
- <itReallyWorks in interface Bar>
second time, they go directly without PMISS
- <staticPropertyOfInterfaceWow in interface Foo>
- <itReallyWorks in interface Bar>
80 /tmp> 
===
Mime
View raw message