Java根据属性类型进行反射


public String reflect(){
HttpServletRequest request = ServletActionContext.getRequest();

Enumeration enumeration = request.getParameterNames();
Class clazz = Product.class;
Product product = new Product();
Map configMap = new HashMap();
try {
while(enumeration.hasMoreElements()){
String queryField = enumeration.nextElement();
String field = queryField.replace("product[0].", "");
String value = request.getParameter(queryField);
if(field.indexOf(".")>=0){
String mapkey = field.split("\\.")[1];
configMap.put(mapkey, value);
}
field = field.equals("pid")?"productid":field;
Field[] fields = clazz.getDeclaredFields();
for(Field f:fields){
if(f.getName().equals(field)){

PropertyDescriptor pd = new PropertyDescriptor(f.getName(), clazz);
//获取属性的类型
Class pclazz = pd.getPropertyType();
//获取该类型参数为字符串的构造函数
Constructor pconstructor = pclazz.getConstructor(String.class);
//获取属性的写方法
Method setMethod = pd.getWriteMethod();
//执行赋值
setMethod.invoke(product, pconstructor.newInstance(value));
}
}

}

} catch (Exception e) {
e.printStackTrace();
}
product.setConfig(configMap);
return SUCCESS;
}

发表评论