# JavaBean模板

导入依赖:

       
            freemarker
            freemarker
            2.3.8
        

bean模板 demo.ftl

package ${packageName};

/**
 *  @author alfred
 *  time : 2018-05-28
 */
public class ${className} {

<#list attrs as a>

    private ${a.type} ${a.field};


<#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};
    }

}

新建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;
    }
}

# JavaBean模板_第1张图片
image

测试


    public static void main(String[] args){

        String path_Dir = "/Users/alfred/Desktop/Tutorial/myfile/";

        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("hobby", "String"));

        Map root = new HashMap();
        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());
        }
    }
 

                            
                        
                    
                    
                    

你可能感兴趣的:(# JavaBean模板)