Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
872 views
in Technique[技术] by (71.8m points)

groovy - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...