使用模板 java
Template template = new SimpleTemplateEngine().createTemplate( new StringReader("<% // This is a comment that will be filtered from output %>\n" + "Hello <%out.println(name);%> !") ); final StringWriter sw = new StringWriter(); template.make([name:'bloodwolf_china').writeTo(sw); println sw.toString();看看SimpleTemplateEngine類
public Template createTemplate(Reader reader) throws CompilationFailedException, IOException { SimpleTemplate template = new SimpleTemplate(); String script = template.parse(reader); template.script = groovyShell.parse(script, "SimpleTemplateScript" + counter++ + ".groovy"); return template; }這兒作了三件事
out.print("Hello "); out.println(name); out.print(" !");三、用groovyShell獲取一個Script對象
public abstract class Script extends GroovyObjectSupport { private Binding binding; public Object getProperty(String property) { try { return binding.getVariable(property); } catch (MissingPropertyException e) { return super.getProperty(property); } } public abstract Object run(); }groovyShell把一段代碼組裝成一個GroovyCodeSource對象,而後調用GroovyClassLoader,CompilationUnit把CodeSource編譯成一個Script對象,run()方法中執行的便是out.print(模板內容)這段代碼。
private static class SimpleTemplate implements Template { protected Script script; public Writable make() { return make(null); } public Writable make(final Map map) { return new Writable() { /** * Write the template document with the set binding applied to the writer. * * @see groovy.lang.Writable#writeTo(java.io.Writer) */ public Writer writeTo(Writer writer) { Binding binding; if (map == null) binding = new Binding(); else binding = new Binding(map); Script scriptObject = InvokerHelper.createScript(script.getClass(), binding); PrintWriter pw = new PrintWriter(writer); scriptObject.setProperty("out", pw); scriptObject.run(); pw.flush(); return writer; } /** * Convert the template and binding into a result String. * * @see java.lang.Object#toString() */ public String toString() { StringWriter sw = new StringWriter(); writeTo(sw); return sw.toString(); } }; } }很清楚了,調用make方法,建立一個Script對象,綁定參數binding = new Binding(map)。