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.
精彩评论