1、创建测试类(BeanTest1.java)
package com.jeff;
import java.lang.reflect.Field;
import java.util.Date;
import com.jeff.entity.Student;
public class BeanTest1 {
public static void main(String[] args) throws Exception {
Student s = new Student();
s.setLoginName("Jeff");
s.setSex(1);
s.setCreateTime(new Date());
System.out.println("转换前:" + s.toString());
s = reflect(s);
System.out.println("转换后:" + s.toString());
}
/**
*
* @description: 遍历属性将null转为""或0
* @author: Jeff
* @date: 2019年12月20日
* @param <T>
* @param o
* @return
* @throws Exception
*/
private static <T> T reflect(T o) throws Exception {
Class<? extends Object> cls = o.getClass();
Field[] fields = cls.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field f = fields[i];
f.setAccessible(true);
System.out.println("属性名:" + f.getName() + ";属性值:" + f.get(o) + ";字段类型:" + f.getType());
if (f.getType() == String.class && f.get(o) == null) {
f.set(o, "");
}
if (f.getType() == Integer.class && f.get(o) == null) {
f.set(o, 0);
}
}
return o;
}
}
2、控制台输出结果