Blog

Metaprogramming means writing programs that manipulate programs. In Groovy, we can use MOP to invoke methods dynamically and synthesize classes and methods on the fly. This can give us the feeling that our object favorably changed its class. Groovy allows metaprogramming for POJOs and POGOs.

Intercepting Methods Using GroovyInterceptable

If Groovy object implements GroovyInterceptable, then its invokeMethod() is called when any of its methods are called—both existing methods and nonexistent methods. That is, GroovyInterceptable’s invokeMethod() hijacks all calls to the object.

If we don’t have the privileges to modify the class source code ,in this case we may decide at runtime to start intercepting calls based on some condition or application state. In these cases, we can intercept methods by implementing the invokeMethod() method on the MetaClass

There are two differences between these two versions of invokeMethod() we implemented on Phone, The first difference is the use of delegate instead of this. The delegate within the intercepting closure refers to the target object whose methods are being intercepted. The second difference is where we call invokeMissingMethod() on the MetaClass instead of calling invokeMethod. We’re already in invokeMethod(), so we should not call it recursively here.