Java根据属性类型进行反射 - 全栈笔记

Java根据属性类型进行反射

任亦伟 JAVA 2015-02-04 46 次浏览 没有评论

01
02
public String reflect(){
03
  HttpServletRequest request = ServletActionContext.getRequest();
04
 
05
  Enumeration<String> enumeration =  request.getParameterNames();
06
  Class clazz = Product.class;
07
  Product product = new Product();
08
  Map<String,String> configMap = new HashMap<String, String>();
09
  try {
10
    while(enumeration.hasMoreElements()){
11
      String queryField = enumeration.nextElement();
12
      String field = queryField.replace("product[0].", "");
13
      String value = request.getParameter(queryField);
14
      if(field.indexOf(".")>=0){
15
        String mapkey = field.split("\\.")[1];
16
        configMap.put(mapkey, value);
17
      }
18
      field = field.equals("pid")?"productid":field;
19
      Field[]  fields = clazz.getDeclaredFields();
20
      for(Field f:fields){
21
        if(f.getName().equals(field)){
22
 
23
          PropertyDescriptor pd = new PropertyDescriptor(f.getName(), clazz);
24
          //获取属性的类型
25
          Class pclazz = pd.getPropertyType();
26
          //获取该类型参数为字符串的构造函数
27
          Constructor<String> pconstructor = pclazz.getConstructor(String.class);
28
          //获取属性的写方法
29
          Method setMethod = pd.getWriteMethod();
30
          //执行赋值
31
          setMethod.invoke(product, pconstructor.newInstance(value));
32
        }
33
      }
34
 
35
    }
36
 
37
  } catch (Exception e) {
38
    e.printStackTrace();
39
  }
40
  product.setConfig(configMap);
41
  return SUCCESS;
42
}
43

发表评论

回顶部