views:

103

answers:

1

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.

+1  A: 

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.

Christoph Metzendorf
Thanks. But what, if I don't know what meta class changes have been made. Think of an application like the Groovy Web Console, where different users execute Groovy scripts. I want these users not to interfere.
cretzel