tags:

views:

424

answers:

3

Would it be possible to use groovy ast transformations code to manipulate java classes?

If yes, please give an example.

If no, please specify why.

A: 

Maybe. Your first issue is going to be to find a Java compiler which offers you an AST. Try the Eclipse compiler; here, you'll just have to map all the types to the ones expected by the Groovy AST transformer. Duck typing is going to help but only if the two ASTs contain compatible information (which I doubt).

After that, you need to find a way to get the AST from the compiler before the bytecode is generated and then a way to inject the modified AST into the compiler again to get bytecode.

All in all, probably not impossible but it will take some work.

Aaron Digulla
+2  A: 

Yes it is possible to use Groovy AST Transformations with Java code. Groovy compiles down to java bytecode and builds on the Java libraries. Interoperability between the two languages is great.

There is a whole section on the groovy site that covers the AST Transformations.

Here is an example of a mixed Java/Groovy application. You have a standard Java Interface and implementation. The groovy classes use the @Delegate AST transformation and also use invokeMethod.

Java classes:

interface IFoo {
    public String someMethod(String arg1);
}

class Foo implements IFoo {
    public String someMethod(String arg1) { 
        arg1+arg1;
    }
}

Groovy classes:

class Bar implements IFoo {
    @Delegate Foo foo = new Foo()
    def otherMethod() {
        someMethod("abcdef")
    }
}

Executing new Bar().otherMethod() would return 'abcdefabcdef'.

Chris Dail
http://groovy.codehaus.org/Category+and+Mixin+transformations is exactly what i would like. Thanks!
elhoim
A: 

A tool that provides source-to-source transformation of Java source code directly is the DMS Software Reengineering Toolkit. DMS is generalized compiler technology that parses code to ASTs, build symbol tables and flow analysis information, enables custom analyzers and transforms to be coded and applied, and then can then regenerate source text from the ASTs, including the original comments.

DMS will actually allow you transform an arbitrarily large set of source files together. This is often needed to allow code changes in one source file, to cause code changes in another.

DMS works with Java, C#, C, C++, COBOL, and many other langauges.

Ira Baxter