SpringMVC数据绑定xx.yy.zz 时的yy对象初始化
SpringMVC数据绑定xx.yy.zz 时的yy对象初始化
Spring Mvc 中的SimpleFormController是专门负责数据绑定的Controller ,当做深层绑定时,xx.yy.zz 如果yy 对象为null
就会抛出空指针.我在前期用如下代码进行初始化
Article article = new Article();
MainType articleType = new MainType();
article.setMainType(articleType);
显尔易见这段代码繁琐的,经过摸索,利用java 反射机制,编写了一个公共方法进行初始化
package com.allcom.base.commons;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import com.allcom.vvgoo.persist.Merchant;
/** *//** *//** *//**
* 初始化对像的属性 ,对于日期型数据将自动填充当前日期
*
* */
public class AutoView {
public static void AutoView(Object command){
if(null!=command){
Class classType = command.getClass();
Field fields[] = classType.getDeclaredFields();
for(int i=0;i<fields.length;i++){
Field field = fields[i];
String fieldName = field.getName();
String typeName =field.getType().getName();
String firstLetter = fieldName.substring(0,1).toUpperCase();
String getMethodName = ”get”+firstLetter+fieldName.substring(1);
String setMethodName = ”set”+firstLetter+fieldName.substring(1);
try {
Method setMethod = classType.getMethod(setMethodName,new Class[]{field.getType()});
Class clazz = Class.forName(typeName);
Object value = clazz.newInstance();
if (null!=value){
setMethod.invoke(command,new Object[]{value});
}
} catch (Exception e) {
}
}
}
}
public static void main(String[] arg){
Merchant merchant = new Merchant();
AutoView view = new AutoView();
view.AutoView(merchant);
System.out.print(Util.dateToString(merchant.getCreateDate(), ”yyyy-MM-dd”));
}
}
其中 Merchant 是任意的一个javaBean,在使用该方法处理后,其中xx.yy.zz 中的yy 对象会自动填充该对象全新的实例

