12.2 Intercepting Methods Using MetaClass

We used ​GroovyInterceptable​ to intercept method calls in Section 12.1, Intercepting Methods Using GroovyInterceptable. That approach is good if we’re the author of the class whose methods we want to intercept. However, that approach won’t work if we don’t have the privileges to modify the class source code or if it is a Java class. Furthermore, 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​.

Let’s rewrite the example from Section 12.1, Intercepting Methods Using GroovyInterceptable, this time using the ​MetaClass​. In this version, the ​Car ...

Get Programming Groovy 2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.