Pradyumna
Pradyumna

Reputation: 1633

Dynamic fields in Groovy for a Java class

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)

Upvotes: 1

Views: 1020

Answers (2)

winstaan74
winstaan74

Reputation: 1131

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

Upvotes: 3

Angel O'Sphere
Angel O'Sphere

Reputation: 2666

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'"   } 

Upvotes: 0

Related Questions