编程语言
首页 > 编程语言> > freeMarker之根据模板生成JAVA代码示例

freeMarker之根据模板生成JAVA代码示例

作者:互联网

首先导入maven依赖:

<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.28</version>
</dependency>

之后新建包,并在该包下编写模板文件test.ftl:

package ${classPath};

public class ${className} {

    private Integer ${Id};
    private String ${userName};
    private String ${passWord};

    public Integer get${Id}(){
        return ${Id};
    }

    public void set${Id}(Integer ${Id}){
        this.${Id} = ${Id};
    }

    public String get${userName}(){
        return ${userName};
    }

    public void set${userName}(String ${userName}){
        this.${userName} = ${userName};
    }

    public String get${passWord}(){
        return ${passWord};
    }

    public void set${passWord}(String ${passWord}){
        this.${passWord} = ${passWord};
    }

}

然后编写运行生成对应java代码类:

package com.json.templates;

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class FreemarkerDemo {
    private static final String TEMPLATE_PATH = "C:\\src\\main\\java\\com\\json\\templates";
    private static final String CLASS_PATH = "C:src\\main\\java\\com\\json\\templates";
    public static void main(String[] args){
        // 创建freemarker配置实例
        Configuration configuration = new Configuration();
        Writer out = null;
        try {
            // 获取模板路径
            configuration.setDirectoryForTemplateLoading(new File(TEMPLATE_PATH));
            //创建数据模型
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("classPath", "com.huawei.cbc.json.templates");
            dataMap.put("className", "User");
            dataMap.put("Id", "Id");
            dataMap.put("userName", "userName");
            dataMap.put("passWord", "passWord");
            // 加载模板文件
            Template template = configuration.getTemplate("test.ftl");
            // 生成数据
            File docFile = new File(CLASS_PATH+"\\"+"User.java");
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
            // 输出文件
            template.process(dataMap, out);
            System.out.println("----创建成功----");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (out != null){
                    out.flush();
                }
            }catch (Exception e){
                e.printStackTrace();
            }

        }
    }
}

最后刷新下项目即可看到新生成的类。

标签:userName,JAVA,String,freeMarker,示例,dataMap,Id,passWord,public
来源: https://www.cnblogs.com/jlutiger/p/11131460.html