导入依赖:
<dependency>
<groupId>freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.8</version>
</dependency>
bean模板 demo.ftl
package ${packageName};
/**
* @author alfred
* time : 2018-05-28
*/
public class ${className} {
<#list attrs as a>
private ${a.type} ${a.field};
</#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
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;
}
}

image
测试
public static void main(String[] args){
String path_Dir = "/Users/alfred/Desktop/Tutorial/myfile/";
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.my.learn.freemarker");
root.put("className", "User");
root.put("attrs", list);
root.put("author", "adams");
Configuration cfg = new Configuration();
String path = ToBean.class.getResource("/").getPath();
try {
cfg.setDirectoryForTemplateLoading(new File(path));
Template template = cfg.getTemplate("/demo.ftl");
StringWriter out = new StringWriter();
template.process(root, out);
System.out.println(out.toString());
File file = new File(path_Dir + "User" + ".java");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
PrintWriter pw = new PrintWriter(fw);
pw.write(out.toString());
pw.flush();
pw.close();
} catch (IOException e) {
System.out.println("Cause==>" + e.getCause());
} catch (TemplateException e) {
System.out.println("Cause==>" + e.getCause());
}
}