地图中的Groovy对象属性 [英] Groovy object properties in map
本文介绍了地图中的Groovy对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
不必从像这样的对象中声明地图中的所有属性:
Instead of having to declare all the properties in a map from an object like:
prop1: object.prop1
难道不能像下面那样将对象放在那里吗?还是实现这一目标的合适方法是什么?
Can't you just drop the object in there like below somehow? Or what would be a proper way to achieve this?
results: [
object,
values: [
test: 'subject'
]
]
推荐答案
object.properties也将为您提供class
object.properties will give you a class
as well
您应该能够:
给出您的POGO对象:
Given your POGO object:
class User {
String name
String email
}
def object = new User(name:'tim', email:'tim@tim.com')
编写一种方法来检查该类并从中获取非合成属性:
Write a method to inspect the class and pull the non-synthetic properties from it:
def extractProperties(obj) {
obj.getClass()
.declaredFields
.findAll { !it.synthetic }
.collectEntries { field ->
[field.name, obj."$field.name"]
}
}
然后,将地图分散到您的结果地图中:
Then, map spread that into your result map:
def result = [
value: true,
*:extractProperties(object)
]
给你
['value':true, 'name':'tim', 'email':'tim@tim.com']
这篇关于地图中的Groovy对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文