Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy - Ignore extra attributes in a map during object instantiation

Tags:

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!

like image 818
Quad64Bit Avatar asked Apr 17 '12 17:04

Quad64Bit


2 Answers

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 
like image 109
Jiankuan Xing Avatar answered Oct 23 '22 20:10

Jiankuan Xing


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) }) } 
like image 41
ataylor Avatar answered Oct 23 '22 20:10

ataylor