Java反射机制

时间:2014-04-29 10:38:46   收藏:0   阅读:472

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 {

//方法1

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;
}

//方法2

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;
}

}

通过反射避免重复代码,将表单获取的值直接传到实体类中

Java反射机制,码迷,mamicode.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!