Search code examples
groovymetaprogramming

How do I undo meta class changes after executing GroovyShell?


For example, if I execute a Groovy script, which modifies the String meta class, adding a method foo()

GroovyShell shell1 = new GroovyShell();
shell1.evaluate("String.metaClass.foo = {-> delegate.toUpperCase()}");

when I create a new shell after that and execute it, the changes are still there

GroovyShell shell2 = new GroovyShell();
Object result = shell2.evaluate("'a'.foo()");

Is there a way to undo all meta class changes after executing the GroovyShell? I tried

shell1.getClassLoader().clearCache();

and

shell1.resetLoadedClasses();

but that did not make a change.


Solution

  • You can use

    GroovySystem.metaClassRegistry.removeMetaClass(String.class);
    

    to revert all changes made to the String meta class.

    Alternatively you could only change the meta class of a certain String instance, thus not all instances of String would be affected.