How to get all property names of a Groovy class? [duplicate]

末鹿安然 提交于 2019-12-21 03:48:08

问题


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.


回答1:


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]



回答2:


Take a look at the MetaClass API.




回答3:


Can you use Java Reflection API?

Take a look at getDeclaredFields of java.lang.Class.

Some kind of tutorial / guide about using Reflection API.



来源:https://stackoverflow.com/questions/2585992/how-to-get-all-property-names-of-a-groovy-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!