groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From John Smiljanic <>
Subject Overriding a static property
Date Thu, 25 Aug 2016 15:54:30 GMT
Groovy 2.4.6

I am trying to override static property access/mutation in a groovy class.
My objective is to read/write static properties from a well defined scope
rather than depending upon the Class/ClassLoader scope.

My current strategy is to use an AST transform to rewrite all static,
mutable fields in my classes to use a scope service.  I was planning to use
the ExpandoMetaClass to accomplish this as follows:

Before transformation:

class Test
   static def test = "foo"

   static def lookupTest() {

After transformation:

class Test
      Test.metaClass.static.getTest = { ->

      Test.metaClass.static.setTest = { Object v ->
         Scope.setValue("test", v)

      Test.test = "foo"

   static def test = "foo"

   static def lookupTest() {

where Scope is an abstraction of a Scope service that I already have
implemented.  For testing with groovy console I implemented the following
simple Scope service:

class Scope {
   // this is a simplification of an abstract scope service
   static Map<String, Object> properties = [:]

   static def getValue(String k) {
   static void setValue(String k, Object v) {
      properties[k] = v

One gotcha that I did notice is that if I don't rewrite all access to the
property (see lookupTest) to include an explicit reference to the static
target then groovy resolves to the actual field rather than using the
getter.  For example, if the field is defined as:

static def test = "foo"

but I set a different value in the static constructor:

Test.test = "bar"

then lookupTest() { test } will print "foo"

and lookupTest() { Test.test } will print "bar".

Is this a bug?

Has anyone attempted anything similar?  Does anyone have other ideas about
how one might accomplish this with groovy?


View raw message