I am trying to intercept all method calls inside Groovy scripts running in a Java environment.
Specially I want to check the return type of all method calls, and if it is X
I want to replace it with Y
.
I know you can intercept using invokeMethod
on the MetaClass, but I can only do that to the script class that I compile. If the script in turn calls a method on class A
then it will create a new MetaClass[A]
that I can't intercept without earlier having manually fetched that MetaClass from the registry and overriding it with a meta method.
I have tried to use GroovySystem.getMetaClassRegistry()
to add listeners for when MetaClasses are created, to add meta methods there, but it seemingly never fires.
I would like this to be automatic, and not in advance having to add an annotation to the methods that I should transform, or knowing which classes' methods I want to transform. All methods that return X
should return Y
.
Can I globally intercept all method calls?
Can I intercept MetaClass creation instead?
Can I add automatic AST transformations?