Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy meta-programming - adding static methods to Object.metaClass

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?

like image 560
knorv Avatar asked Sep 22 '09 22:09

knorv


People also ask

What is MetaClass in Groovy?

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.

What is the name of the class in Groovy that allows you to add properties and methods to it dynamically?

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.

Does Groovy require semicolon?

​ semicolons are optional in Groovy, you can omit them, and it's more idiomatic to remove them.

What are Groovy properties?

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.


1 Answers

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()

like image 50
Rhysyngsun Avatar answered Nov 09 '22 14:11

Rhysyngsun