读取form数据时,java反射的一点应用

来源:互联网 发布:电气工程软件 编辑:程序博客网 时间:2024/06/06 06:57

package com.gis.biz;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

public class ObjectRef {

 

//用反射填充对象,得到对象,
 public static Object getInstance(Class ccc, Map map)
   throws ClassNotFoundException, InstantiationException,
   IllegalAccessException, SecurityException, NoSuchFieldException,
   NoSuchMethodException, IllegalArgumentException, InvocationTargetException{
      String cname = ccc.getName();
      Object obj = null;
    Class c = Class.forName(cname);
  obj = c.newInstance();
  Set set = map.keySet();
  Iterator it = set.iterator();
  while(it.hasNext()){
   String methodName = (String)it.next();
   System.out.println();
   Field ff = c.getDeclaredField(methodName);
   Object value= map.get(methodName);
   String mName = "set"+methodName.substring(0, 1).toUpperCase()+methodName.substring(1);
   Method m = c.getDeclaredMethod(mName, ff.getType());
   m.invoke(obj, value);
  }
  return obj;
 }

//把form 表单中的数据转化成map里的属性--值
 public static Map getMap(HttpServletRequest request){
  Map map = new HashMap();
  Enumeration en =request.getParameterNames();
  while(en.hasMoreElements()){
   String formName = (String) en.nextElement();
   String l = request.getParameter(formName);
   map.put(formName, l);
  }
  return map;
 
 }
}

这是本人在做web 项目时 的一点小的应用,能够省去大量的request.getParameter,希望大家能再给点意见,有什么不足帮忙补充

 

谢谢

 

原创粉丝点击