Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot set readonly property: class for class in groovy when initializing with map

Tags:

groovy

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 
like image 795
Ambuj Jauhari Avatar asked Oct 26 '25 23:10

Ambuj Jauhari


1 Answers

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
like image 192
injecteer Avatar answered Oct 29 '25 07:10

injecteer