1)首先下载FreeMaker的jar包(下载后导入工程)
下载地址:(我使用的版本是2.3.26)
http://www.apache.org/dyn/closer.cgi/incubator/freemarker/engine/2.3.26-incubating/binaries/apache-freemarker-2.3.26-incubating-bin.tar.gz
maven依赖
org.freemarker
freemarker
2.3.26-incubating
2)测试项目目录结构
3)Person.ftl
package ${packageName};
/**
* @author xzw #if>
*/
public class ${className} {
private ${a.type} ${a.field};
#list>
public void set${a.field?cap_first}(${a.type} ${a.field}){
this.${a.field} = ${a.field};
}
public ${a.type} get${a.field?cap_first}(){
return this.${a.field};
}
#list>
}
4) Attr.java
package com.JobData;
public class Attr{
public String field;
public String type;
public Attr(String field, String type){
this.field = field;
this.type = type;
}
public String getField(){
return this.field;
}
public String getType(){
return this.type;
}
public void setField(String field){
this.field = field;
}
public void setType(String type){
this.type = type;
}
}
5)CodeGenerator.java
package com.main;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.JobData.Attr;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class CodeGenerator {
@SuppressWarnings("deprecation")
public static void main(String[] args){
List list = new ArrayList();
list.add(new Attr("username", "String"));
list.add(new Attr("password", "String"));
list.add(new Attr("age", "int"));
list.add(new Attr("text", "String"));
Map root = new HashMap();
root.put("packageName", "com.JobData");
root.put("className", "Person");
root.put("attrs", list);
root.put("author", "xzw");
Configuration cfg = new Configuration();
/*path模板路径为编译类的路径*/
String path = "D:/WorkSpace/FreeMaker/bin/com/ftl";
try {
cfg.setDirectoryForTemplateLoading(new File(path));
Template template = cfg.getTemplate("/Person.ftl");
/*判断该目录是否存在,不存在则新建该目录*/
File dir = new File("D:/WorkSpace/FreeMaker/src/com/java/com/JobData/");
if(!dir.exists()){
dir.mkdirs();
}
OutputStream out = new FileOutputStream(
new File(dir+"Person.java"));
template.process(root, new OutputStreamWriter(out));
} catch (IOException e) {
System.out.println(e.getMessage());
} catch (TemplateException e) {
System.out.println(e.getMessage());
}
}
}
简单好用,适合很多重复的代码生成,降低出错率。