I am trying to create a class and initialize all the values with a default value. So i have this pojo in groovy, and i have created initializeWithDefaults method to initialize all the values. I am trying to pass map in the 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 i keep getting the error
in thread "main" groovy.lang.ReadOnlyPropertyException: Cannot set readonly property: class for class: com.ambuj.domain.MDS
You are getting the error, as you are trying to override a class propery of a *HashMap which is provided as a getClass() and of course not writeable.
You should take care, what properties you are trying to copy. A simple experiment in Groovy console looked like (pay attention to !prop.synthetic):
class MDS {
// your 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 the output:
Result: default.id:default.mdsName:default.mdsDomain
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With