Groovy Meta Programming

In TCL, you can get the code of a method / procedure at runtime, modify it, and insert it back.

Is this possible in Groovy? I know it is possible to wrap the original method, but I (unfortunately) assume that in groovy the source of the methods is not available at runtime, right?

Example

: imagine the following (not quite good) exmaple

def someMethod() {
   //some complex code I don't have the source
   println "debug"
   //some more complex code
}

      

If now I want to change operator println

to operator log

. I can't replace the whole method because I either don't have the source or I don't want to risk it being different in the next version and so I would overwrite it with an older source.

Thanx to Jayan. Now I know that this can be handled via AST transformations, but it seems to me that this is more complicated than it should be.

If I could just get the source through metaprogramming and change it ...

OK. I've already heard people say that I need a parser to modify it, and exactly what AST gives me is already parsed code. But to be honest, I think a simple regex on the source is often good enough; -)

+3


source to share


1 answer


First of all, to make things clear: Runtime Metaprogramming means you have a self-updating program. He changes himself while working. This is usually done by changing the metaclass. Compiletime Metaprogramming means modifying a program before running it by "extending" the compiler. Typically, this is done with AST transformations.

Groovy provides JVM bytecode for execution. There may or may not be a source file available to do this, but generally there is no runtime structure that stores the source. There is a meta-class mapping to AST, but basically it looks for a suitable source file in the classpath and compiles the AST from it. If the source is not available to you, this will not work.



Even if the source is available, it won't give you the change function you are looking for. The new class has to be compiled, and then something like hotswapping will be used to replace the class.

Groovy is not an imaging system like Smalltalk.

+2


source







All Articles