依赖的jar包:velocity-1.6. , velocity-tools-generic-2. , commons-collections-3. , commons-lang-2.
新建好模版文件 (文件格式没有限定,我这里测试使用这种格式生成一个javaBean) 。放在WEBROOT/template目录下.文件代码如下:
package ${package} /* 这里替换的字符穿是包名 **/
public class ${className} {/* 这里需要替换的是 类名称*/
/** 循环该类的所有属性,columnDatas 是个List<Entity>,Entity是一个类,这个类有两个属性,一个是 type,
标识该字段的类型,colName是该字段的名称 这里循环输出这个List<Entity> */
#foreach( $item in $!{columnDatas} )
private $ $ ;
#set( $end=$() ) /* 计算属性的长度*/
#set( $str=$( 1 ,$end ) )
#set( $start = $(0,1).toUpperCase() ) /* 首字母大写 */
public void set$start$str($ $){
this.$ = $ ;
}
#set( $get = "get")
#if($ == "boolean" ) /* 如果是字段类型是boolean类型,get方法就是is开头*/
#set( $get = "is")
#end
public $ $get$start$str(){
return this.$;
}
#end
}
现在模版类写好了,需要去替换这个模版类,将此类生成到一个文件夹中。
public class Demo {
/* 获取工程的目录,WEBRoot*/
public static String getRootPath() {
String rootPath = "";
try {
File file = new File(("/").getFile());
rootPath = ().getParent();
rootPath = (rootPath, "utf-8");
return rootPath;
} catch (Exception e) {
();
}
return rootPath;
}
/** 在static块中 初始化 VelocityEngine 类,这里面的参数我还不是很清楚,请阅读者 在评论中告知,*/
static VelocityEngine ve;
static {
try {
// 获取文件模板根路径
String templateBasePath = getRootPath() + "\\template";
Properties properties = new Properties();
(Velocity.RESOURCE_LOADER, "file");
("" ,
"Velocity File Resource Loader");
(Velocity.FILE_RESOURCE_LOADER_PATH,
templateBasePath);
(Velocity.FILE_RESOURCE_LOADER_CACHE, "true");
(
"", "30");
(Velocity.RUNTIME_LOG_LOGSYSTEM_CLASS ,
".Log4JLogChute");
("." ,
"");
("", "true");
VelocityEngine velocityEngine = new VelocityEngine();
(properties);
ve = velocityEngine;
} catch (Exception e) {
();
}
}
static String CONTENT_ENCODING = "UTF-8" ;
public static void main(String[] args) throws Exception {
Template template = ( "", CONTENT_ENCODING );
File file = new File( "C:\\" + "" ); /* 定义输出替换文件的目录 */
FileOutputStream fos = new FileOutputStream(file);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos,CONTENT_ENCODING) );
VelocityContext context = new VelocityContext() ; /* 定义输出类中需要替换的对象 */
( "className" , "Person" ) ; /* 替换类名*/
( "package" , "" ) ; /* 替换报名 */
List<Entity> entities = new ArrayList<Entity>() ;
( new Entity( "String" , "name" ) ) ;
( new Entity( "String" , "address" ) ) ;
( new Entity( "boolean" , "flag" ) ) ;
("columnDatas", entities ) ; /* 替换属性名称,和setter,getter */
(context, writer); /* 执行替换方法*/
();
();
();
}
}
以上代码生成的文件就是这样:
package
public class Person {
private String name ;
public void setName(String name){
= name ;
}
public String getName(){
return ;
}
private String address ;
public void setAddress(String address){
= address ;
}
public String getAddress(){
return ;
}
private boolean flag ;
public void setFlag(boolean flag){
= flag ;
}
public boolean isFlag(){
return ;
}
}