@Override
  public void intercept(IMethodInvocation invocation) throws Throwable {
    MetaClassRegistry registry = GroovySystem.getMetaClassRegistry();
    List<MetaClass> originalMetaClasses = new ArrayList<>();

    for (Class<?> clazz : classes) {
      originalMetaClasses.add(registry.getMetaClass(clazz));
      MetaClass temporaryMetaClass = new ExpandoMetaClass(clazz, true, true);
      temporaryMetaClass.initialize();
      registry.setMetaClass(clazz, temporaryMetaClass);
    }

    try {
      invocation.proceed();
    } finally {
      for (MetaClass original : originalMetaClasses)
        registry.setMetaClass(original.getTheClass(), original);
    }
  }
@author Luke Daley
@author Peter Niederwieser
spock-core/src/main/java/org/spockframework/runtime/extension/builtin/ConfineMetaClassChangesInterceptor.java