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.

Klaim
  • 67,274
  • 36
  • 133
  • 188
  • 1
    This is actually not a duplicate of http://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 '16 at 20:58
  • @pczeus If you know how to get names and values, then you also know how to get names only. – Mark Rotteveel Sep 17 '16 at 06: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 '16 at 01:27

2 Answers2

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]
eklektek
  • 1,083
  • 1
  • 16
  • 31
3

Take a look at the MetaClass API.

uchuugaka
  • 12,679
  • 6
  • 37
  • 55
armandino
  • 17,625
  • 17
  • 69
  • 81