Java 反射
Java反射机制
package com.utils; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Enumeration; import javax.servlet.http.HttpServletRequest; public class ReflectUtil { public static <T> T initlize(Class<T> clazz, HttpServletRequest request) throws Exception { T t = clazz.newInstance(); Field[] fields = clazz.getDeclaredFields();// 变量的对象 for (Field field : fields) { String filedName = field.getName();// 变量对象的名字 Class<?> fieldType = field.getType();// 变量的数据类型 Enumeration<String> enumeration = request.getParameterNames();// 获取表单文本的的对象 while (enumeration.hasMoreElements()) { String pName = enumeration.nextElement();// 获取表单文本对象的名称 if (filedName.equals(pName)) { String preflexStr = filedName.substring(0, 1); String sufflexStr = filedName.substring(1); String writeMethodStr = "set" + preflexStr.toUpperCase() + sufflexStr;// 方法名 Method writeMethod = clazz.getDeclaredMethod( writeMethodStr, new Class<?>[] { fieldType });// 造方法 String pValue = request.getParameter(pName); if (fieldType.toString().equals("int")) { writeMethod.invoke(t, Integer.valueOf(pValue) .intValue()); continue; } else if (fieldType.newInstance() instanceof Date) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat( "yyyy-MM-dd"); Date date = simpleDateFormat.parse(pValue); System.out.println("********" + pValue); System.out.println("+++++++++" + date); writeMethod.invoke(t, date); continue; } else if (fieldType.newInstance() instanceof Integer) { writeMethod.invoke(t, Integer.valueOf(pValue) .intValue()); continue; } writeMethod.invoke(t, pValue); } } } return t; } public static <T> T initlize01(Class<T> clazz, HttpServletRequest request) throws Exception { T t = clazz.newInstance(); PropertyDescriptor[] propertyDscriptors = Introspector.getBeanInfo( clazz).getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDscriptors) { String fileName = propertyDescriptor.getName(); Method writeMothod = propertyDescriptor.getWriteMethod(); if (writeMothod != null) { Enumeration<String> enumeration = request.getParameterNames(); while (enumeration.hasMoreElements()) { String pName = enumeration.nextElement(); if (fileName.equals(pName)) { String pValue = request.getParameter(pName); writeMothod.invoke(t, pValue); } } } } return t; } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。