groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "KARR, DAVID" <dk0...@att.com>
Subject RE: Dynamic adding properties to class
Date Tue, 26 May 2015 18:33:54 GMT
> -----Original Message-----
> From: Schalk Cronjé [mailto:ysb33r@gmail.com]
> Sent: Tuesday, May 26, 2015 8:21 AM
> To: users@groovy.incubator.apache.org
> Subject: Dynamic adding properties to class
> 
> This should be straight-forward, but it is failing for me (at least
> on
> 2.3x and 2.4.x). What am I doing wrong?
> 
> Here is some code sufficiently distilled.
> 
> class A {
>    void addSomeProp( String name,String key, def value ) {
>      if(metaClass.getMetaProperty(name)==null) {
>        metaClass."${name}" = [:]
>      }
>      metaClass."${name}"[key]=value.toString()
>    }
> }

Perhaps try "metaClass.hasProperty(name)" instead?

> A a = new A()
> a.addSomeProp( 'info','version',3)  // Fails with: No such
> property:
> info for class: groovy.lang.MetaClassImpl
> 
> The idea is to add a map (of name) if it does not exist, and then
> add
> items into the map.
> 
> --
> Schalk W. Cronjé
> Twitter / Ello / Toeter : @ysb33r

Mime
View raw message