1

I'm new to groovy and still learning my way around. Is there an easy way to get POJO property values in groovy using dot notation? For example, I have the following POJO:

public class MyPOJO {
        protected String name;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }

}

In groovy, I would like to get the value of the name field as follows:

def doSomething (MyPOJO mpj) {
    def name = mpj.name
    // do something
}

The above does not work. I know that i could still use java getters and setters, but I would like to be able to get to a point where I can dynamically pull pojo values like so:

def doSomething (MyPOJO mpj, String propertyName) {
    def propertyValue = mpj.'${propertyName}'
    // do something
}

I'm trying to avoid using java reflection. Thanks for the help!

SWS3D
  • 109
  • 9
  • 1
    Can you explain what does not work for you? Your code works for me. – Michal Kordas Apr 17 '15 at 05:59
  • 2
    That's exactly how it should work with Groovy - with a minor correction, you need to use a GString (double quotes) when accessing a property dynamically `def propertyValue = mpj."${propertyName}"` – stempler Apr 17 '15 at 06:53

1 Answers1

0

Michal - apologies... the first code snippet was working, the second wasn't.

stempler - that worked! this was gnawing on me. corrected snippet:

def doSomething (MyPOJO mpj, String propertyName) {
    def propertyValue = mpj."${propertyName}"
    // do something
}
SWS3D
  • 109
  • 9
  • if you pass "name" as value for parameter propertyName it works, in other cases it will rise an exception for attempt to access a missing property. – user1708042 Apr 24 '15 at 13:24