The Using the Delegating Meta Class page talks about techniques to change the behavior of existing classes by replacing the meta class in use. However, the Delegating Meta Class effects all loaded classes.

The Proxy Meta Class allows us to replace the meta class in use by a class but in a well defined scope. This technique would be more appropriate for temporary behavior replacements such as

This example shows how we can create a proxy meta class for the String class and intercept its method invocations.

import org.codehaus.groovy.runtime.InvokerHelper

class ProxyMetaClassTest extends GroovyTestCase
{
    void testProxyMetaClass()
    {
        def proxy = ProxyMetaClass.getInstance(String.class);
        proxy.interceptor = new MyInterceptor()

        def text = "hello world"

        assertEquals "hello world", text.toString()

        proxy.use {
            assertEquals "changed hello world", text.toString()
        }

        assertEquals "hello world", text.toString()
    }
}

class MyInterceptor implements groovy.lang.Interceptor
{
    Object beforeInvoke(Object a_object, String a_methodName, Object[] a_arguments)
    {
    }

    boolean doInvoke()
    {
        return true
    }

    Object afterInvoke(Object a_object, String a_methodName, Object[] a_arguments, Object a_result)
    {
         return "changed ${a_result}"
    }
}


For more detail on using the ProxyMetaClass, see http://groovy.codehaus.org/Using+the+Proxy+Meta+Class+in+depth.