工作遇到接口文档要做一堆接口每个实体类有很多字段,就写了一个简单的脚本,在此记录一下以便处理类似的问题。
类似这种字段表格,第一列$$$是自己添加的换行标志。
$$$ | name | required | length | desc | comment |
$$$ | name | y | 50 | 姓名 | 客户姓名 |
$$$ | age | y | 51 | 年龄 | 客户年龄 |
$$$ | weight | y | 52 | 体重 | 客户体重 |
$$$ | height | n | 53 | 身高 | 客户身高 |
去掉第一行,复制到ide变成
//根据 接口文档栏位项目名称 中文名称 补充说明 生成XMLmodel类
//每行以$$$开头 第一列为$$$
public static void generateCommonApiModel(String str) {
int indexOfPP = 0;
//每行开头
String linePrefix = "$$$";
//字段名过滤的字符 例如 ..name
String varNameSkipStr = "[..]";
//截取的列
int [] contentIndexes = new int[]{1,3,4};
String rstContent = "";
while (str.indexOf(linePrefix, indexOfPP) > -1) {
//按照 linePrefix 截取每行
int currPP = str.indexOf(linePrefix, indexOfPP);
String line;
if (currPP + linePrefix.length() < str.length()) {
int nextPP = str.indexOf(linePrefix, currPP + linePrefix.length());
if (nextPP > 0) {
line = str.substring(currPP + linePrefix.length(), nextPP);
indexOfPP = nextPP;
} else {
//最后一个
line = str.substring(currPP + linePrefix.length());
indexOfPP = str.length()-1;
}
} else {
//最后一个
line = str.substring(currPP + linePrefix.length());
indexOfPP = str.length()-1;
}
String[] cells = line.split("[\t]");
if (contentIndexes.length > 2) {
//注释内容
String content ="/**\n";
content += " * "+cells[contentIndexes[0]];
if (cells.length > contentIndexes[2]) {
for (int i = contentIndexes[2]; i < cells.length; i ++) {
content += " "+cells[i].replaceAll("\n", "");
}
}
content+= "\n */\n";
//字段内容
String varName = cells[contentIndexes[0]].replaceAll(varNameSkipStr, "");
content += "@XmlElement(name = \""+varName+"\")\n";
// content +="@XmlJavaTypeAdapter(CDataAdapter.class)\n";
content += "private String "+ StringUtils.toCamelCase(varName) +";";
content +="\n";
rstContent += content;
System.out.print("");
}
}
System.out.println(rstContent);
}
public static void main(String[] args) {
String str = "$$$\tname\ty\t50\t姓名\t客户姓名\n" +
"$$$\tage\ty\t51\t年龄\t客户年龄\n" +
"$$$\tweight\ty\t52\t体重\t客户体重\n" +
"$$$\theight\tn\t53\t身高\t客户身高\n"
;
generateCommonApiModel(str);
}
输出:
/**
* name 姓名 客户姓名
*/
@XmlElement(name = "name")
private String name;
/**
* age 年龄 客户年龄
*/
@XmlElement(name = "age")
private String age;
/**
* weight 体重 客户体重
*/
@XmlElement(name = "weight")
private String weight;
/**
* height 身高 客户身高
*/
@XmlElement(name = "height")
private String height;