是否可以通过在Apache Velocity中定义模板来生成Java代码?

时间:2012-06-14 06:47:10

标签: java apache velocity

我需要使用Velocity Template概念生成Java文件。你能指导一下吗?

java代码应包含一些方法,导入和变量......

谢谢, Easwar

1 个答案:

答案 0 :(得分:4)

使用velocity / java部分,您或多或少需要这样做:

// factory and an engine instance
VelocityEngineFactory velocityEngineFactory = new VelocityEngineFactory();
VelocityEngine engine = velocityEngineFactory.createVelocityEngine();
// now you need to give the variables you wanna have access from velocity script
VelocityContext context = new VelocityContext(properties);

ByteArrayOutputStream temp = new ByteArrayOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(temp));
// generate the result, where scriptString is the velocity script
engine.evaluate(context, bufferedWriter, null, scriptString);
bufferedWriter.flush();
textResultant = temp.toString();

所以你可以创建一个脚本,加载它并以编程方式处理它。

相关问题