需求:
前人写的上传生成PDF,标题没有显示完全有null显示在上面
问题:
调用别人家接口不知道为null是哪个字段造成的
期望:
标题显示完整,不出现null
做法:
对实体类属性遍历,对所有为空的属性,赋值为空字符串
Code:
//实体类
TestUtil test = new TestUtil();
test.setId("007");
test.setMobile("13967867888");
for (Field f : test.getClass().getDeclaredFields()) {
f.setAccessible(true);
//判断字段是否为空,并且对象属性中的基本都会转为对象类型来判断
if (f.get(test111) == null){
f.set(test111, "778878");
System.out.println(f.getName());
}
}
扩展:
对字段去空格,为空的操作返回"":
/**
* 对字符串去除空格,如果字符串为null,则返回""
* @param str :输入字符串
* @return :trim后结果
*/
public static String trim(String str) {
if (null == str) {
return "";
}
return str.trim();
}