Is there a way to make groovy ignore extra attributes in a map during object instantiation? Example:
class Banana{ String name } def params = [name:'someGuy', age:13] new Banana(params)
In this example, groovy throws a No such property: age exception (obviously because age isn't defined in the Banana class. Without resorting to manually mapping only the desired attributes from the map to the constructor of the Banana class, is there a way to tell Banana to ignore the extra attributes?
I noticed that Grails domain classes do not suffer from this problem, and I would like the same behavior here!
Thanks for your help and advice!
There is a simpler way to deal with this case.
In your bean, just implement a trait
trait IgnoreUnknownProperties { def propertyMissing(String name, value){ // do nothing } } class Person implements IgnoreUnknownProperties { String name } map = ["name": "haha", "extra": "test"] Person p = new Person(map) println p.name
Unfortunately, there's no built in way to do this in groovy. Grails does it by generating its own constructors for domain objects. A simple workaround is to use a constructor like this:
Banana(Map map) { metaClass.setProperties(this, map.findAll { key, value -> this.hasProperty(key) }) }
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