0

Based on this question I created a Groovy class that will have dynamic properties.

class MyDynamic {
  def propertyMissing( String name, value ) {
    this.metaClass."$name" = value
    value
  }
}

So far all good, now I can set some non-existent property with success

MyDynamic dyna = new MyDynamic()
dyna.someProp = new Date()

My problem begins when I have another instance with the same name of property, but with another type

MyDynamic dyna2 = new MyDynamic()
dyna2.someProp = "0" //GroovyCastException: Cannot cast object '0' with class 'java.lang.String' to class 'java.util.Date'

Actually I need this because I'm creating objects with the result of a query without knowing the table and the column. I get the name of the column with the ResultSetMetaData and add the property to the instance of the dynamic object. Later I will use this object to export all the properties and values. In different tables I have the same column name, but with different types.

So my question is: how can I reset this metaClass when I'm done with the instance to not conflict with other instance?

Community
  • 1
  • 1

1 Answers1

2

Why not a Expando, a Map or a simple container:

class Dynamic {
  def properties = [:]
  void setProperty( String name, value ) {
    properties[name] = value
  }

  def getProperty(String property) { properties[property] }
}

d = new Dynamic()

d.name = "yeah"
assert d.name.class == String

d.name = new Date()
assert d.name.class == Date
Will
  • 14,348
  • 1
  • 42
  • 44