Cannot set readonly property: class for class in groovy when initializing with map -
i trying create class , initialize values default value. have pojo in groovy, , have created initializewithdefaults method initialize values. trying pass map in constructor
class mds { string id string mdsname string name string mdstype string mdscontext string mdsdatetime string mdsdomain public static void initializewithdefaults() { mds datasegmentiddef = new mds() map<string, object> prop = datasegmentiddef.properties prop.each { map.entry entry-> entry.value = "default-${entry.key}" } mds datasegmentid = new mds(prop) } }
but keep getting error
in thread "main" groovy.lang.readonlypropertyexception: cannot set readonly property: class class: com.ambuj.domain.mds
you getting error, trying override class
propery of *hashmap
provided getclass()
, of course not writeable.
you should take care, properties trying copy. simple experiment in groovy console looked (pay attention !prop.synthetic
):
class mds { // props @override string tostring() { "$id:$mdsname:$mdsdomain" } static void initializewithdefaults() { mds mds = mds.class.declaredfields.inject( new mds() ){ mds mds, prop -> if( !prop.synthetic ) mds[ prop.name ] = "default.$prop.name" mds } println mds } } mds.initializewithdefaults()
and output:
result: default.id:default.mdsname:default.mdsdomain
Comments
Post a Comment