0

I need to run some code whenever a property value is retrieved, so naturally it made sense to define the getProperty method in my class. This method will get automatically called whenever a property value is retrieved. Here's roughly what I have in my class:

class MyClass
{
  def getProperty(String name)
  {
   // Run some code ...

    return this.@"${name}"
  }
}

The problem with the above method occurs when someone tries to make the following call somewhere:

MyClass.class

This call ends up in the getProperty method looking for a property named "class", however, there is not actual property named "class" so we get a MissingFieldException.

What would be the correct way to implement running code whenever a property value is retrieved and deal with these kind of situtations.

Harry Muscle
  • 2,247
  • 4
  • 38
  • 62

2 Answers2

3

Best is not to have a getProperty method if not needed. If you need one and you want to fall back on standard Groovy logic, then you can use return getMetaClass().getProperty(this, property), as can be found in GroovyObjectSupport. This will cover more than just fields.

blackdrag
  • 6,413
  • 2
  • 26
  • 38
  • Hi, I think this might be what I'm looking for. Would you be able to provide an example or expand more on your answer, especially how to fall back to standard Groovy logic? – Harry Muscle Feb 19 '15 at 20:09
  • it's really just that line to fall back. Normally you handle your special cases and the, if non of them matches, you go the meta class route. Maybe https://github.com/groovy/groovy-core/blob/master/src/main/groovy/lang/Closure.java#L274 is a good example. Here you see for example that `delegate` is handled directly and if non of the special cases is matched, the code calls into the metaclass – blackdrag Feb 20 '15 at 03:52
2

This seems to be a common problem with this method. Map has the same issue. The developers of groovy got around the problem with Map by saying you need to use getClass() directly.

Michael Rutherfurd
  • 13,815
  • 5
  • 29
  • 40