xtendxpand

How to call Java code from Xpand?


I want to call an arbitrary Java method from an Xpand template (e.g. a static method). How can I do this?


Solution

  • You need to create a mapping for the Java method in the template. This excellent post explains the process in detail http://pettergraff.blogspot.de/2009/11/how-to-write-extension-in-xtend-for.html

    Example:

    CalledJavaCode.java

    package template;
    
    public class CalledJavaCode {
        public static String evaluate(Object o) {
            return "some evaluation";
        }
    }
    

    Template.xpt

    //Xtend mapping for Java in template file
    String eval(Object this) : JAVA
        template.CalledJavaCode.evaluate(java.lang.Object);
    
    // Template.xpt usage of mapping
    «FOREACH attribute AS a»
        «eval(a)»
    «ENDFOREACH»