HiveBrain v1.2.0
Get Started
← Back to all entries
patternMajor

Returning Groovy class fields as a map

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
mapfieldsreturningclassgroovy

Problem

I want to get a map of all the fields in a class (aka value object) in a generic way. The following works fine for me:

class Baz {
  String foo = "foo2"
  int bar = 2

  public Map asMap() {
    def map = [:] as HashMap
    this.class.getDeclaredFields().each {
      if (it.modifiers == java.lang.reflect.Modifier.PRIVATE) {
        map.put(it.name, this[it.name])
      }
    }
    return map
  }
}


But this doesn't feel like the proper way. Is there a better approach?

Solution

Another alternative (very similar to Matt's) is to use the synthetic field property (which is set for default class properties, but not for your own defined props):

class Baz {
  String foo = "foo2"
  int bar = 2

  public Map asMap() {
    this.class.declaredFields.findAll { !it.synthetic }.collectEntries {
      [ (it.name):this."$it.name" ]
    }
  }
}

Code Snippets

class Baz {
  String foo = "foo2"
  int bar = 2

  public Map asMap() {
    this.class.declaredFields.findAll { !it.synthetic }.collectEntries {
      [ (it.name):this."$it.name" ]
    }
  }
}

Context

StackExchange Code Review Q#8801, answer score: 28

Revisions (0)

No revisions yet.