title: Groovy: dynamically add properties to groovy classes from inside class methods
body: <p>I have the following code:</p>
  
  <pre><code>class MyClass {
      def myMethod() {
          variable = "I am a variable"
      }
  
      def propertyMissing(String name) {
          println "Missing property $name"
      }
  }
  
  MyClass myClass = new MyClass();
  myClass.myProperty
  myClass.myMethod();
  </code></pre>
  
  <p>At myClass.myProperty, <code>Missing property myProperty</code> was printed out to the console.</p>
  
  <p>But then in <code>myClass.myMethod()</code>, groovy makes no attempt to go to <code>propertyMissing</code> but instead just throws a </p>
  
  <pre><code>groovy.lang.MissingPropertyException: No such property: variable for class: MyClass
  </code></pre>
  
  <p>Some search online indicates that it is because <code>myClass.myProperty</code> calls a getter method, which redirects to propertyMissing.</p>
  
  <p>I am guessing that within class methods, groovy doesn't go through getter methods for variables and that's why propertyMissing is not getting called?</p>
  
  <p>Is there a way to achieve what I want to do using the dynamic <code>propertyMissing</code>, or <code>getProperty</code>, or anything like that?</p>
  
  <p>P.S. I don't want to do <code>def variable = ...</code> or <code>String variable = ...</code> in myMethod. I am hoping that the syntax within <code>myMethod</code> will stay as <code>variable = ...</code>, but adding anything outside of that method is acceptable.</p>