Java 如何获取 Groovy 类的所有属性名称?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2585992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get all property names of a Groovy class?
提问by Klaim
The title ask it all : How to get all property names of a Groovy class?
标题问了一切:如何获取 Groovy 类的所有属性名称?
Is it even possible? I thought I could use collection syntaxes with classes too be it don't seem to work.
甚至有可能吗?我想我也可以在类中使用集合语法,但它似乎不起作用。
回答by sourcerebels
Can you use Java Reflection API?
你可以使用 Java 反射 API 吗?
Take a look at getDeclaredFields of java.lang.Class.
看看java.lang.Class 的 getDeclaredFields。
回答by armandino
Take a look at the MetaClass API.
回答by user2196409
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.
我正在使用 groovy 编译器 2.4 我得到一个java.util.LinkedHashMap
包含所有属性及其通过调用getProperties()
groovy 对象返回的值。
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]