I've encountered a Groovy meta-programming problem which I'm unable to solve.
When adding the static method foo() to the class FooBar, then FooBar.foo() works as expected:
FooBar.metaClass.static.foo = {
println "hello"
}
FooBar.foo()
However, I instead add the same static method foo() to the class Object, then FooBar.foo() fails with an MissingMethodException:
Object.metaClass.static.foo = {
println "hello"
}
FooBar.foo()
// groovy.lang.MissingMethodException:
// No signature of method: FooBar.foo() is applicable for argument types:
// () values: []
Why is that? Shouldn't Object.metaClass.static.foo = { .. }
add foo() also to FooBar?
A MetaClass within Groovy defines the behaviour of any given Groovy or Java class. The MetaClass interface defines two parts. The client API, which is defined via the extend MetaObjectProtocol interface and the contract with the Groovy runtime system.
Groovy provides a metaClass property in all its classes. The ExpandoMetaClass class provides numerous ways to transform an existing class at runtime. For example, we can add properties, methods, or constructors.
semicolons are optional in Groovy, you can omit them, and it's more idiomatic to remove them.
When a Groovy class definition declares a field without an access modifier, then a public setter/getter method pair and a private instance variable field is generated which is also known as "property" according to the JavaBeans specification.
In order to get the behavior you're looking for you need to call ExpandoMetaClass.enableGlobally()
Keep in mind doing this has a bigger memory footprint than normal meta-programming.
http://groovy.codehaus.org/api/groovy/lang/ExpandoMetaClass.html#enableGlobally()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With