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