Can I implement Groovy’s getProperty in Java Objects
I have a mixed Java/Groovy project, and I’m trying to add some “sugar” to my Java objects to make the Groovy side cleaner.
Is it possible to implement Object getProperty(String) in a Java class and have Groovy see it when accessing properties on that instance?
I have a failing test case as follows:
// HasProperty.java
public class HasProperty {
public Object getProperty(String name) {
return "pie";
}
}
// TestHasProperty.groovy
class HasPropertyTest {
@org.junit.Test
public void testCanGetProperty() {
def h = new HasProperty()
assert h.name == "pie"
}
}
The test fails without fanfare:
groovy.lang.MissingPropertyException: No such property: name for class: HasProperty
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:50)
at org.codehaus.groovy.runtime.callsite.GetEffectivePojoPropertySite.getProperty(GetEffectivePojoPropertySite.java:63)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGetProperty(AbstractCallSite.java:227)
at [...]
This is Groovy 1.8.6 and Java 6.
To make this work without implementing GroovyObject as per @tim_yates’s answer, you can wrap the object with a very simple groovy object. For example: