简体   繁体   English

如何在Grails域对象中获得声明的属性?

[英]How do I get declared properties in Grails domain objects?

I'm trying to convert Grails domain objects to Map. 我正在尝试将Grails域对象转换为Map。 I have a code that do it for POGOs using Apache Commons BeanUtils' PropertyUtils.describe . 我有一个使用Apache Commons BeanUtils的PropertyUtils.describe为POGO做到的代码。 However, using the same code on domain objects just doesn't work because of all the stuff added by the Grails framework. 但是,由于Grails框架添加了所有内容,因此无法在域对象上使用相同的代码。 I want to be able to convert any object to a Map with only the declared fields just like how Grails converts domain objects to JSON. 我希望能够仅使用声明的字段将任何对象转换为Map,就像Grails如何将域对象转换为JSON一样。 What features can help me achieve this? 哪些功能可以帮助我实现这一目标?

I would suggest something like this inside your domain class: 我会在您的域类中建议这样的事情:

    public Map asMap() {
        this.class.declaredFields.findAll { !it.synthetic }.collectEntries {
          [ (it.name):this."$it.name" ]
        }
    }

There are other questions about the same problem, did you try this? 对于同一问题还有其他疑问,您尝试过吗? Grails / Groovy - Domain Object - Map of its Properties Grails / Groovy-域对象-属性图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM