开发者

Using groovy AST Transform for modifying java

开发者 https://www.devze.com 2022-12-10 12:17 出处:网络
Would it be possible to use groovy ast transformations code to manipulate java classes? If yes开发者_Go百科, please give an example.

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

If yes开发者_Go百科, please give an example.

If no, please specify why.


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'.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消