title: Adding a property to a Groovy object from Java
body: <p>I would like to be able to add a property to an instance of String object using Groovy's metaprogramming capabilities from Java.</p>
  
  <p>To do this from Groovy is simple:</p>
  
  <pre><code>class GroovyClass {
      def getDynamicString() {
          def myString = "hello"
          myString.metaClass.dynamicProperty = "there"
          return myString
      }
  }
  </code></pre>
  
  <p>Here is my Spock test case:</p>
  
  <pre><code>def "should add dynamic property"() {
      GroovyClass groovyClass = new GroovyClass()
  
      when:
      def theString = groovyClass.getDynamicString()
      then:
      theString == "hello"
      theString.dynamicProperty == "there"
  }
  </code></pre>
  
  <p>However, I would like to do the same thing from Java and run it through the same test. As I understand, Groovy adds extra properties and methods (such as getMetaClass) to the JDK classes like String but I'm not sure exactly how or when it does this. I have found that the following solution works but it seems cumbersome to initialise a GroovyShell and to write the metaprogramming code as a string.</p>
  
  <pre><code>public String getDynamicString()
  {
      String myString = "hello";
      GroovyShell shell = new GroovyShell();
      shell.setVariable("myString", myString);
      shell.setVariable("theDynamicPropertyValue", "there");
      shell.evaluate("myString.metaClass.dynamicProperty = theDynamicPropertyValue");
      return myString;
  }
  </code></pre>
  
  <p>Is there a way to do the above without using shell.evaluate - i.e. by calling the Groovy library methods from Java directly?</p>