反射将Bean中属性为null的设置为""

1、利用反射将Java Bean中string类型属性值为null的设为""

 1 SomeClass obj = new SomeClass();
 2 Class c = SomeClass.class;
 3 Field[] fields = c.getDeclaredFields();
 4 for(int i = 0; i < fields.length; i++)
 5 {
 6     String fieldName = fields[i].getName();
 7     fieldName = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
 8 
 9     try
10     {
11         Method getM = c.getMethod("get" + fieldName);
12         String strVal = (String) getM.invoke(obj);
13         if(strVal == null)
14         {
15             Method setM = c.getMethod("set" + fieldName, String.class);
16             setM.invoke(obj, "");
17         }
18     }
19     catch (Exception ex)
20     {
21         LOGGER.error("Java Reflect Error " + ex.toString());
22     }
23 }
原文地址:https://www.cnblogs.com/huoxiayu/p/7612472.html