前言
以前非常羡慕那些会写自动生成代码的高手,觉得他们好厉害;可以解放他们的时间,做他们想做的事,而不是一直在麻木的重复性劳动。现在,拖互联网的福,可以上网搜到这类代码,便下载下来尝试运行。结果成功了,兴奋之余,将代码贴在这儿,以备忘。
准备工作
下载一个freemark的jar包,注意版本;此前下了一个2.2.28,结果运行报错,后换成2.3.22就正常运行了。
目录贴上
介绍:
这里的demo.ftl是模板文件,Atrr.java是字段实体类,用于存放字段类型,字段名,和字段注释,Generate.java就是自动生成的发动机啦。
代码
demo.ftl
java
package ${packageName};
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class ${className} {
<#list attrs as a>
private ${a.type} ${a.field}; // ${a.comment}
</#list>
<#list attrs as a>
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>
}
Attr.java
java
public class Attr {
private String field; //字段名
private String type; //字段类型
private String comment; //注释
public Attr(String field, String type, String comment){
this.field = field;
this.type = type;
this.comment = comment;
}
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
Generate.java
java
public class Generate {
public static void main(String[] args) throws IOException, TemplateException{
List<Object> list = new ArrayList<Object>();
list.add(new Attr("username", "String", "用户名"));
list.add(new Attr("password", "String", "密码"));
list.add(new Attr("age", "int", "年龄"));
list.add(new Attr("hobby", "String", "兴趣爱好"));
Map<String,Object> root = new HashMap<String, Object>();
root.put("packageName", "com.shixun.model");
root.put("className", "User");
root.put("attrs", list);
Configuration cfg = new Configuration();
String path = System.getProperty("user.dir") + "\\src\\com\\shixun\\generate";
cfg.setDirectoryForTemplateLoading(new File(path));
Template template = cfg.getTemplate("/demo.ftl");
// printConsole(root, template);
printFile(root, template);
}
//输出到文件
private static void printFile(Map<String, Object> root, Template template) throws IOException, TemplateException {
String path = System.getProperty("user.dir") + "\\src\\com\\shixun\\model";
File file = new File(path,"User.java");
if(!file.exists()) file.createNewFile();
FileWriter fw = new FileWriter(file);
template.process(root, fw);
fw.close();
}
//输出到控制台
private static void printConsole(Map<String, Object> root, Template template)
throws TemplateException, IOException {
StringWriter out = new StringWriter();
template.process(root, out);
System.out.println(out.toString());
}
}