今天在项目中遇到一个需求:将取值为空的String类型的字段设置为“无”。
这样在页面的表单中就不会出现一片空白了。
想了想应该可以通过反射机制对多个字段进行批量处理。
不多说,上代码:
PmIntentMVO io = new PmIntentMVO(); Field[] fields = PmIntentMVO.class.getDeclaredFields(); try{ for(Field field : fields){ field.setAccessible(true); if(field.getType().getName().equals(java.lang.String.class.getName())){ if(field.get(io)==null||"".equals(field.get(io))){ field.set(io, "无"); } } } }catch(IllegalAccessException ie){ ie.printStackTrace(); }
这里有两个地方需要注意:
1. get、set函数的参数必须是字段所属类的实例;
2. 使用get、set方法之前需要调用setAccessible方法,不然抛出异常。