1
votes

Is there a way I can create a Java class with a pair of "general" getter/setter methods such as

public Object get(String name);
public void set(String name, Object object);

and make Groovy translate statements such as

myObject.foo = 'bar' 

to

myObject.set("foo", "bar")?

(myObject being an instance of the Java class having the get(String) and set(String, Object) methods)

2
Just curious, why would you want to do this? It seems like you're just making things more complicated, since this is essentially what the groovy bean property accessors already provide. - Rob Hruska
The "why" part is slightly tricky.. Java is the language in which I can write classes, but my customers use those classes in their Groovy programs. I ran into this situation where I'd like to expose a Java class whose properties are not known at compile-time and change at runtime. A crude way is to make my object implement Map and ask users to do obj['foo']=bar, but I thought there may be better ways.. didn't know of these "bean property accessors".. will try them as suggested in one of the answers and get back thx.. - Pradyumna

2 Answers

3
votes

Have your java class extend groovy.lang.GroovyObjectSupport, which provides implementations of getProperty and setProperty, or impleemnt to the interface groovy.lang.GroovyObject

0
votes

You have to write two methods in Groovy (assuming you derive your Groovy class from your Java class):

def getProperty(String name) { "This is the property '$name'"   }   
void setProperty(String name, value) { println "You tried to set property '$name' to '$value'"   }