Where it all starts

Say you have a Groovy code like

println 'hi'

As explained in Groovy Backstage, there is bytecode generated to achieve the desired behaviour of printing to stdout.

The easiest way of looking at the generated bytecode is to groovyc your Groovy source to a class file and process it with a Java Decompiler (e.g. JAD). See also: From source code to bytecode

The resulting code looks as follows (only the relevant snippet):

...
Object aobj[] = { "hi" };
ScriptBytecodeAdapter.invokeMethod(this, "println", ((Object) (aobj)));
...

Invocation scheme

There is a delegation scheme like

MetaClass and MetaClassRegistry

Invoker calls invokeMethod(...) on the MetaClass of our class (with exceptions, see below). It finds this MetaClass by looking it up in the MetaClassRegistry. The Invoker holds a single instance of this registry.

When working with the MetaClassRegistry, InvokerHelper.getInstance().getMetaRegistry() is the only instance, you should ever use.

Exceptions (when MetaClass.invokeMethod(...) is not used):

MetaClass.invokeMethod(...) finally cares for the invokation, either by reflection or by dynamic bytecode generation. Dynamic bytecode generation is supposed to be faster. For a class MyClass it generates gjdk.groovy.lang.MyClass_GroovyReflector with an invoke method.

Does MyClass_GroovyReflector contain methods according to MyClass.groovy that can be called directly (question)

The cool thing about MetaClass is that you can dynamically add or remove methods to it. One can even replace the whole MetaClass in the MetaClassRegistry. See ProxyMetaClass for an example.

back to Groovy Backstage