ruby 版,JavaBean的另一种优雅写法——Builder的代码生成器

template="public class "

attr_types =[]
attr_names = []
index=0

File.open("Test.txt"){
 |f|
 file_name=nil
 file_obj=nil
 cls_name=nil
 attr_name=nil
 f.each_line do |line|
 line="#{line}".gsub("\n","")
 if"#{f.lineno}"=="1"
	cls_name=line
	file_name="#{line}"+".java"
	file_obj=File.open(file_name,"w+")
	puts "#{template}"
	template+=cls_name +"{ \n\n"
	
	template += "\tprivate #{cls_name}(){}\n\n"

# print all its attr_nams
else
	attr_array=line.split(":")
	attr_type = attr_array[0]
	attr_name = attr_array[1]
	attr_types[index] = attr_type;
	attr_names[index] = attr_name;
	
	index += 1

	template += "\tprivate " + attr_type + " " + attr_name+";\n"
	
	
end
end
	template += "\n"
	
	# generate gets...
	0.upto(index-1) {|i|
		attr_type = attr_types[i]
		attr_name = attr_names[i]
		template += "\tpublic #{attr_type} get" + attr_name[0].upcase + attr_name[1..attr_name.size-1] + "(){\n"
		template += "\t\treturn #{attr_name};\n"
		template += "\t}\n\n"
	}
	
	# generate builder
	
	template += "\tpublic static Builder{\n"
	instance_name = cls_name[0].upcase + cls_name[1..cls_name.size-1]
	template +="\t\tprivate #{cls_name} #{instance_name} = new #{cls_name}();\n"
	
	template += "\n"
	
	# generate sets...
	0.upto(index-1){|i|
		attr_type = attr_types[i]
		attr_name = attr_names[i]
		
		template += "\t\tpublic Builder set" + attr_name[0].downcase + attr_name[1..attr_name.size-1] + "(#{attr_type} #{attr_name}){\n"
		template += "\t\t\t#{instance_name}.#{attr_name} = #{attr_name};\n"
		template += "\t\t\treturn this;\n"
		template += "\t\t}\n\n"	
	}
	
	# generate getModel
	template += "\t\tpublic #{cls_name} get#{cls_name}(){\n"
	template += "\t\t\treturn #{instance_name};\n"
	template +="\t\t}\n"
	
	template += "\n\t}\n"
	
	template += "\n}\n"
	
	puts template
	file_obj.puts template
}
	


上面为ruby源代码

使用该ruby脚本,应该要提供配置文件,如:

Test.txt

Person 第一样为生成Bean的类名,也就是Java的文件名
String:name   其他几项为属性的类型及名称,以冒号隔开
int:age
int:sex


最后生成的java文件为:

 public class Person{  



private Person(){}


private String name;
private int age;
private int sex;


public String getName(){
return name;
}


public int getAge(){
return age;
}


public int getSex(){
return sex;
}


public static Builder{
private Person person = new Person();


public Builder setName(String name){
person.name = name;
return this;
}


public Builder setAge(int age){
person.age = age;
return this;
}


public Builder setSex(int sex){
person.sex = sex;
return this;
}


public Person getPerson(){
return person;
}


}


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值