15

The title ask it all : How to get all property names of a Groovy class?

Is it even possible? I thought I could use collection syntaxes with classes too be it don't seem to work.

3
  • 1
    This is actually not a duplicate of stackoverflow.com/questions/1477706/groovy-property-iteration because this question is asking only for the property names, not the name and values for the purpose of assignment.
    – pczeus
    Sep 16, 2016 at 20:58
  • @pczeus If you know how to get names and values, then you also know how to get names only. Sep 17, 2016 at 6:33
  • 1
    @MarkRotteveel That's Incorrect. By calling getProperties() you are getting both names and values. It does not give the option to get names only. Yes you can keySet() the result, but you have already paid the price of Groovy calling all getters() and retrieving the values. My point is there is another option in Groovy to get only the property names without paying the penalty of getting the values. Many cases it does not matter, but regardless this is not an actual duplicate question since it is asking for names only.
    – pczeus
    Sep 18, 2016 at 1:27

2 Answers 2

27

I am using groovy compiler 2.4 I get a java.util.LinkedHashMap containing all the properties and their values returned by calling getProperties() on a groovy object.

class PropertyDemoClass {
    int firstProperty = 1;
    String secondProperty = "rhubarb"
    String thirdProperty = "custard"
}

PropertyDemoClass demoClass = new PropertyDemoClass()
println demoClass.getProperties().toString()

which results in:

[firstProperty:1, secondProperty:rhubarb, class:class PropertyDemoClass, thirdProperty:custard]
1
  • A little example snippet of code would be an awesome addition... Sep 3, 2015 at 1:46
3

Take a look at the MetaClass API.

Not the answer you're looking for? Browse other questions tagged or ask your own question.