改进Tools.java工具类
import java.lang.reflect.Field; import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.beanutils.ConvertUtils;
public class Tools { public static Object initBean(Class cls,HttpServletRequest request) { Object o = null; try { o = cls.newInstance(); Field[] fields = cls.getDeclaredFields(); for (Field field : fields) { String fieldName = field.getName(); Method method = cls.getDeclaredMethod("set"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1), new Class[]{field.getType()}); String value = request.getParameter(fieldName); if(value==null) continue; method.invoke(o, new Object[]{ConvertUtils.convert(value, field.getType())}); } } catch (Exception e) { // TODO: handle exception
System.out.println(e); } return o; } public static void main(String[] args) throws Exception { Class cls = Class.forName("com.accp.bean.UserinfoBean"); Object o = cls.newInstance(); Field[] fields = cls.getDeclaredFields(); for (Field field : fields) { String fieldName = field.getName(); Method method = cls.getDeclaredMethod("set"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1), new Class[]{field.getType()}); String value = "1"; method.invoke(o, new Object[]{ConvertUtils.convert(value, field.getType())}); } } }
|
里面有两行代码我们进行了改进,使其可以动态调用非纯String类型的类
一:Method method = cls.getDeclaredMethod("set"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1), new Class[]{field.getType()}); 我们原来的代码在最后是 new Class[]{String.Class}
二:在反射调用的时候用了method.invoke(o, new Object[]{ConvertUtils.convert(value, field.getType())}); 我们原来的代码在最后是 new Object[]{value}
最重要的是我们要导入 数据类型强制转换器的那个包 具体做法:
顺次打开:Borland\JBuilder2006\thirdparty\jakarta-struts-1.1-lib
把里面的十个压缩包复制,放在我们工程下(自己建立一个lib文件夹放里面)
然后:右键工程-bulid Path-Configure bulid Path-点击进去后在里面的Libraries点击Add JARS 选择刚才放进来的包 OK 刷新
阅读(551) | 评论(0) | 转发(0) |