问题:有大量类似于theProductId这样名字的字符串需要转换成the_product_id这种数据库column名的形式。
思路:见到(见)大写字母(缝)就插入(插)一个“_”字符(针)进去,最后把所有字母都转换为小写。
解决办法:递归,字符串操作——见缝插针。
方法如下:
public static String toDbFormat(String theString, String insertString, int i) {
StringBuilder sb = new StringBuilder(theString);
String result = theString;
if (i < sb.length()) {
if (Character.isUpperCase(sb.charAt(i))) {
sb.insert(i, insertString);
i = i + 2;
} else {
i++;
}
result = toDbFormat(sb.toString(), insertString, i);
}
return result.toLowerCase();
}
实际应用——在接口自动化测试框架中根据model类为mybatis文件夹中的xml文件自动生成result部分:
public static void createXmlOut(Object object) throws IOException{
//生成mybatis文件夹中xml文件的result部分
FileWriter writer= new FileWriter("D:\\xmlOut.txt");
@SuppressWarnings("rawtypes")
Class clz = object.getClass();
for (java.lang.reflect.Field field : clz.getDeclaredFields()) {
String target = "<result property=\""+field.getName()+"\" column=\""+toDbFormat(field.getName(), "_", 0)+"\" />";
writer.append(target+"\r\n");
}
writer.flush();
writer.close();
}
测试方法(这里SomeModel替换为测试框架中实际的model类):
public static void main(String[] args) throws IOException {
SomeModel someModel = new SomeModel();
createXmlOut(someModel);
}
执行测试方法后就可以在你的D盘xmlOut.txt文件中看到生成的结果了。完整测试代码如下:
package com.netease.lede.qa.util; import java.io.FileWriter;
import java.io.IOException; import com.netease.lede.qa.model.duobao.TbDuobaoCoinDetail; public class CreateResultXMLUtil {
public static String toDbFormat(String theString, String insertString, int i) {
// 将变量名转成数据库列名形式
StringBuilder sb = new StringBuilder(theString);
String result = theString;
if (i < sb.length()) {
if (Character.isUpperCase(sb.charAt(i))) {
sb.insert(i, insertString);
i = i + 2;
} else {
i++;
}
result = toDbFormat(sb.toString(), insertString, i);
}
return result.toLowerCase();
} public static void createXmlOut(Object object) throws IOException {
// 生成mybatis文件夹中xml文件的result部分
FileWriter writer = new FileWriter("D:\\xmlOut.txt");
@SuppressWarnings("rawtypes")
Class clz = object.getClass();
for (java.lang.reflect.Field field : clz.getDeclaredFields()) {
String target = "<result property=\"" + field.getName() + "\" column=\""
+ toDbFormat(field.getName(), "_", 0) + "\" />";
TylanStringUtil.log(target);
writer.append(target + "\r\n");
}
writer.flush();
writer.close();
} public static void main(String[] args) throws IOException {
TbDuobaoCoinDetail tbDuobaoCoinDetail = new TbDuobaoCoinDetail();
createXmlOut(tbDuobaoCoinDetail);
}
}