Groovy:在飞行中的属性 [英] Groovy: on the fly properties

查看:167
本文介绍了Groovy:在飞行中的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javascript中,您可以使用属性a和b定义一个对象,如下所示:

  myObj = {a:'a' ,b:'b'} 

然后你可以像这样添加属性c

  myObj.c ='c'

什么是Groovy的等价物?我必须使用metaClass吗?

使用案例:Grails中的JSON转换器不会为响应添加瞬态属性,我只想将随机属性附加到我的对象列表的每个元素。

  def myObj [a:'a',b:'b'] 
myObj.c ='c '

您也可以将行为附加到闭包,例如

  myObj.sayHello = { - > println'Hi'} 

然后像调用方法一样调用它:

  myObj.sayHello()


In Javascript you can define an object with properties a and b like so:

myObj={a:'a',b:'b'}

and then you can add a property c like so

myObj.c = 'c'

whats the equivalent of that in Groovy? Do I have to use metaClass?

Use case: JSON converters in Grails do not add transient properties to the response, i would like to just attach a random property to each element of my object list.

解决方案

You can use a Map, which has similar syntax and behavior:

def myObj [a:'a', b:'b']
myObj.c = 'c'

You can also attach behavior with Closures, e.g.

myObj.sayHello = { -> println 'Hi' }

and then call it like a method:

myObj.sayHello()

这篇关于Groovy:在飞行中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆