1

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
  • 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. Commented Aug 24, 2011 at 15:53
  • 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.. Commented Aug 25, 2011 at 14:17

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.