title: Iterating an object's own properties in Groovy?
body: <p>I have created a class that allows the resulting object to have arbitrary properties added to it. The class also has some predefined properties. In a method of the class I want to be able to iterate over all properties owned by the instance of the object.</p>
  
  <p>Here is an example class definition:</p>
  
  <pre><code>import groovy.json.*
  
  class Foo {
      private Map props = [:]
  
      String bar = "baz"
      def myNumber = 42
  
      void propertyMissing(String name, Object value) {
          this.props[name] = value
      }
  
      def propertyMissing(String name) {
          return this.props[name]
      }
  
      def toJsonString() {
          def outObject = [:]
  
          // I want to do something like this
          this.properties.each { k, v -&gt;
              if (this.isOwnProperty(k) &amp;&amp; k != 'props') {
                  outObject[k] = v
              }
          }
  
          outObject = outObject + this.props
  
          return JsonOutput.toJson(outObject)
          // Should return a string like:
          // {"bar":"baz", "myNumber":42, "someDynamicProperty":"value"}
          //
          // This string should not contain the "class" and "metaClass"
          // properties.
      }
  }
  </code></pre>
  
  <p>Is there a way to do what I am wanting to do?</p>
  
  <p><strong>Edit:</strong>
  One of my goals is to not have to explicitly name my predefined properties in the <code>toJsonString</code> method. I want to be able to add new predefined properties at a later date without having to remember to update the <code>toJsonString</code> method.</p>
  
  <p><strong>Edit (24 October 2011):</strong></p>
  
  <p>The accepted answer gave me the information I needed. However, it still required me to name the properties I don't want included in the JSON string. Extending the answer a little bit solves this problem:</p>
  
  <pre><code>def outObject = Foo.declaredFields.findAll {
      // 'it' is a Field object returned by
      // http://download.oracle.com/javase/1,5,0/docs/api/java/lang/Class.html#getDeclaredFields()
      !it.synthetic &amp;&amp;
      it.getModifiers() != java.lang.reflect.Modifier.PRIVATE
  }.collectEntries { v -&gt;
      [ (v.name) : this[v.name] ]
  }
  </code></pre>
  
  <p>For this to work, you must explicitly specify the modifiers for your class properties. That is <code>String bar = "baz"</code> in my example should be <code>public String bar = "baz"</code> in order for it to be included in the JSON string.</p>