简体   繁体   English

Groovy:动态属性

[英]Groovy: on the fly properties

In Javascript you can define an object with properties a and b like so:在 Javascript 中,您可以定义具有属性 a 和 b 的 object,如下所示:

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

and then you can add a property c like so然后你可以像这样添加一个属性 c

myObj.c = 'c'

whats the equivalent of that in Groovy? 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.用例: Grails 中的 JSON 转换器不会向响应添加瞬态属性,我只想将随机属性附加到我的 object 列表的每个元素。

You can use a Map , which has similar syntax and behavior:您可以使用Map ,它具有类似的语法和行为:

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

You can also attach behavior with Closures, eg您还可以使用闭包附加行为,例如

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

and then call it like a method:然后像方法一样调用它:

myObj.sayHello()

Quoting from Using methodMissing and propertyMissing :引用Using methodMissing 和 propertyMissing

Groovy also supports propertyMissing for dealing with property resolution attempts. Groovy 还支持用于处理属性解析尝试的 propertyMissing。 For a getter you use a propertyMissing definition that takes a String argument:对于 getter,您使用带有 String 参数的 propertyMissing 定义:

  class Foo {
       def propertyMissing(String name) { name }
    }
    def f = new Foo()

    assertEquals "boo", f.boo

For a setters you add a second propertyMissing definition that takes a value argument:对于 setter,您添加第二个 propertyMissing 定义,该定义采用 value 参数:

class Foo {
   def storage = [:]
   def propertyMissing(String name, value) { storage[name] = value }
   def propertyMissing(String name) { storage[name] }
}
def f = new Foo()
f.foo = "bar"

assertEquals "bar", f.foo

As with methodMissing you will likely want to dynamically register new properties at runtime to improve the performance of you code.与 methodMissing 一样,您可能希望在运行时动态注册新属性以提高代码的性能。

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

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