import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang.StringUtils;
import 请看我的上一篇博客时间工具类.DateUtil;(这个是我的上一个博客写的工具类自己导入)
/**
*
* humf
*/
public class ReflectUtil {
/**
* 对象的复制
*
* <br>
* @version 2013-9-23 下午6:45:41
* @param source 参照对象
* @param target 目标对象
*/
public static void copy(Object source, Object target) {
if(null != source || target != null){
try {
if(!(source instanceof Map) && !(source instanceof HttpServletRequest)){
ReflectUtil.beanCopy(source, target);
}else{
Field[] fields = target.getClass().getDeclaredFields();
for (Field field : fields) {
// 这里是获取bean属性的类型
Class<?> beanType = field.getType();
String paraName = field.getName();
Object value = null;
if(source instanceof Map) {
value = ((Map)source).get(paraName);
} else if(source instanceof HttpServletRequest){
value = ((HttpServletRequest)source).getParameter(paraName);
}
if(null==value){
//为 null不做处理
continue;
}else if(value instanceof Map) {
value = ((Map)value).get(paraName);
} else if(value instanceof HttpServletRequest){
value = ((HttpServletRequest)value).getParameter(paraName);
}else if (beanType == java.util.Date.class) {
// 设置参数类型,此类型应该跟javaBean里边的类型一样
// 处理日期类型不匹配问题
value = DateUtil.dateStringToDate(value.toString(),"yyyy-MM-dd HH:mm:ss");
}else if (beanType == Integer.class || beanType == int.class) {
// 处理int类型不匹配问题
value = new Integer(value.toString());
}else if (beanType == Long.class || beanType == long.class) {
// 处理long类型不匹配问题
value = new Long(value.toString());
}else if (beanType == Boolean.class || beanType == boolean.class) {
// 处理boolean类型不匹配问题
value = new Boolean(value.toString());
}else if (beanType == Float.class || beanType == float.class) {
// 处理float类型不匹配问题
value = new Float(value.toString());
}else if (beanType == Double.class || beanType == double.class) {
// 处理double类型不匹配问题
value = new Double(value.toString());
}
String setMethodName = "set" + paraName.substring(0, 1).toUpperCase() + paraName.substring(1);
// 第一个参数是传进去的方法名称,第二个参数是 传进去的类型;
Method m = target.getClass().getMethod(setMethodName, beanType);
// 第二个参数是传给set方法数据
m.invoke(target, value);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Bean中对象的复制
*
* @param baseForm
* 参照Bean对象
* @param objForm
* 目标Bean对象
*/
public static void beanCopy(Object baseForm, Object objForm) {
// 取得拷贝对象的所有域
Field[] fieldsBase = baseForm.getClass().getDeclaredFields();
Field.setAccessible(fieldsBase, true);
// 取得目标对象的所有域
Field[] fieldsObj = objForm.getClass().getDeclaredFields();
Field.setAccessible(fieldsObj, true);
for (int i = 0; i < fieldsObj.length; i++) {
// 取得域名称
Field fieldObj = fieldsObj[i];
for (int j = 0; j < fieldsBase.length; j++) {
Field fieldBase = fieldsBase[j];
// 比较两域名称是否一致
if (fieldObj.getName().equals(fieldBase.getName())) {
// 取得域名称并将第一个字母大小
String fieldName = fieldObj.getName();
String firstChar = fieldName.substring(0, 1).toUpperCase();
fieldName = firstChar + fieldName.substring(1);
// 取得目标对象中的set方法
Method methodObj = null;
Method methodGet = null;
// 源对象属性值
Object resultObj = null;
try {// 获得get方法
// 取得参照对象中的get方法
methodGet = baseForm.getClass().getMethod("get" + fieldName);
} catch (Exception e) {
}
if (null != methodGet) {
try {// 获得set方法并进行copy
methodObj = objForm.getClass().getMethod("set" + fieldName, new Class[] { fieldObj.getType() });
// 执行参照对象的get方法并取得返回值
resultObj = methodGet.invoke(baseForm);
// 执行目标对象的set方法并进行设值
if (null != resultObj)
methodObj.invoke(objForm, new Object[] { resultObj });
} catch (Exception e) {
}
}
break;
}
}
}
}
public static List<Object> getAllFieldAndValue(List<?> dataList) throws Exception {
List<Object> allInfoList = new ArrayList<Object>();
if (null != dataList && dataList.size() > 0) {
List<String> filedNameArr = new ArrayList<String>();
List<String> getMethodNameArr = new ArrayList<String>();
boolean flag = false;// 是否存在 serialVersionUID
Class<?> cls = dataList.get(0).getClass();// 当前类型
Field[] fs = cls.getDeclaredFields();// 当前类型的所有字段
for (int i = 0; i < fs.length; i++) {
String filedName = fs[i].getName();
if (!"serialVersionUID".equals(filedName)) {
filedNameArr.add(filedName);
String firstLetter = filedName.substring(0, 1).toUpperCase(); // 获得字段第一个字母大写
String getMethodName = "get" + firstLetter + filedName.substring(1); // 转换成字段的get方法
getMethodNameArr.add(getMethodName);
// getMethodNameArr.add(0, getMethodName) ;
} else {
flag = true;
}
}
if (flag) {
List<String> filedNameArrNew = new ArrayList<String>();
for (int i = 0; i < filedNameArr.size(); i++) {
if (null != filedNameArr.get(i)) {
filedNameArrNew.add(filedNameArr.get(i));
}
}
List<String> getMethodNameArrNew = new ArrayList<String>();
for (int i = 0; i < getMethodNameArr.size(); i++) {
if (null != getMethodNameArr.get(i)) {
getMethodNameArrNew.add(getMethodNameArr.get(i));
}
}
allInfoList.add(filedNameArrNew);
allInfoList.add(getMethodNameArrNew);
List<Object[]> allDataList = new ArrayList<Object[]>();
for (int i = 0; i < dataList.size(); i++) {
Object[] filedValueArr = new Object[getMethodNameArrNew.size()];// 当前对象所有方法对应的值
for (int j = 0; j < getMethodNameArrNew.size(); j++) {
Method getMethod = cls.getMethod(getMethodNameArrNew.get(j), new Class[] {});
Object value = getMethod.invoke(dataList.get(i), new Object[] {}); // 这个对象字段get方法的值
filedValueArr[j] = value;
}
allDataList.add(filedValueArr);
}
allInfoList.add(allDataList);
} else {
allInfoList.add(filedNameArr);
allInfoList.add(getMethodNameArr);
List<Object[]> allDataList = new ArrayList<Object[]>();
for (int i = 0; i < dataList.size(); i++) {
Object[] filedValueArr = new Object[getMethodNameArr.size()];// 当前对象所有方法对应的值
for (int j = 0; j < getMethodNameArr.size(); j++) {
Method getMethod = cls.getMethod(getMethodNameArr.get(j), new Class[] {});
Object value = getMethod.invoke(dataList.get(i), new Object[] {}); // 这个对象字段get方法的值
filedValueArr[j] = value;
}
allDataList.add(filedValueArr);
}
allInfoList.add(allDataList);
}
}
return allInfoList;
}
public static List<Object> getAllFieldAndValue2(List<?> dataList, String[] dataString) throws Exception {
try {
List<Object> allInfoList = new ArrayList<Object>();
if (null != dataList && dataList.size() > 0) {
List<String> filedNameArr = new ArrayList<String>();
List<String> getMethodNameArr = new ArrayList<String>();
boolean flag = false;// 是否存在 serialVersionUID
Class<?> cls = dataList.get(0).getClass();// 当前类型
Field[] fs = cls.getDeclaredFields();// 当前类型的所有字段
for (int i = 0; i < fs.length; i++) {
String filedName = fs[i].getName();
if (!"serialVersionUID".equals(filedName)) {
filedNameArr.add(filedName);
String firstLetter = filedName.substring(0, 1).toUpperCase(); // 获得字段第一个字母大写
String getMethodName = "get" + firstLetter + filedName.substring(1); // 转换成字段的get方法
// 判断getXX是否要显示
if (dataString != null) {
for (int j = 0; j < dataString.length; j++) {
if (getMethodName.equals(dataString[j].toString())) {
getMethodNameArr.add(getMethodName);
break;
}
}
} else {
getMethodNameArr.add(getMethodName);
}
// getMethodNameArr.add(0, getMethodName) ;
} else {
flag = true;
}
}
if (dataString != null && dataString.length > 0) {
List<String> ar = new ArrayList<String>(); // 若传入的列值不为空
// 还原为指定的顺序
for (int i = 0; i < dataString.length; i++) {
for (int j = 0; j < getMethodNameArr.size(); j++) {
if (dataString[i].equals(getMethodNameArr.get(j))) {
ar.add(dataString[i]);
}
}
}
getMethodNameArr = ar;
}
if (flag) {
List<String> filedNameArrNew = new ArrayList<String>();
for (int i = 0; i < filedNameArr.size(); i++) {
if (null != filedNameArr.get(i)) {
filedNameArrNew.add(filedNameArr.get(i));
}
}
List<String> getMethodNameArrNew = new ArrayList<String>();
for (int i = 0; i < getMethodNameArr.size(); i++) {
if (null != getMethodNameArr.get(i)) {
getMethodNameArrNew.add(getMethodNameArr.get(i));
}
}
allInfoList.add(filedNameArrNew);
allInfoList.add(getMethodNameArrNew);
List<Object[]> allDataList = new ArrayList<Object[]>();
for (int i = 0; i < dataList.size(); i++) {
Object[] filedValueArr = new Object[getMethodNameArrNew.size()];// 当前对象所有方法对应的值
for (int j = 0; j < getMethodNameArrNew.size(); j++) {
Method getMethod = cls.getMethod(getMethodNameArrNew.get(j), new Class[] {});
Object value = getMethod.invoke(dataList.get(i), new Object[] {}); // 这个对象字段get方法的值
filedValueArr[j] = value;
}
allDataList.add(filedValueArr);
}
allInfoList.add(allDataList);
} else {
allInfoList.add(filedNameArr);
allInfoList.add(getMethodNameArr);
List<Object[]> allDataList = new ArrayList<Object[]>();
for (int i = 0; i < dataList.size(); i++) {
Object[] filedValueArr = new Object[getMethodNameArr.size()];// 当前对象所有方法对应的值
for (int j = 0; j < getMethodNameArr.size(); j++) {
Method getMethod = cls.getMethod(getMethodNameArr.get(j), new Class[] {});
Object value = getMethod.invoke(dataList.get(i), new Object[] {}); // 这个对象字段get方法的值
filedValueArr[j] = value;
}
allDataList.add(filedValueArr);
}
allInfoList.add(allDataList);
}
return allInfoList;
}
} catch (Exception e) {
return null;
}
return null;
}
public static List<Object> getAllFieldAndValueObject(List<?> dataList) throws Exception {
try {
List<Object> listValue = new ArrayList<Object>();
List<Object[]> dataValueList = new ArrayList<Object[]>();
for (int i = 0; i < dataList.size(); i++) {
if(dataList.get(i) instanceof List){
List tempList = (List<String>) dataList.get(i);
int len = tempList.size();
Object[] objList = new Object[len];
for (int j = 0; j < objList.length; j++) {
objList[j] = tempList.get(j);
}
dataValueList.add(objList);
}else{
dataValueList.add((Object[])dataList.get(i));
}
}
listValue.add(null);
listValue.add(null);
listValue.add(dataValueList);
return listValue;
} catch (Exception e) {
return null;
}
}
/**
* 获得所有字段和对应的值
* Jun 20, 2012 2:41:51 PM
* @param obj
* @return Map
*/
public static Map<String, String> getAllFieldAndDataMap(Object obj) {
Map<String, String> map = new HashMap<String, String>();
return getAllFieldAndDataMap(obj, map);
}
/**
* 获得所有字段和对应的值
* Oct 25, 2012 10:28:31 PM
* @param obj
* 需要反射的对象
* @param map
* 保存数据的Map
* @return
*/
public static Map<String, String> getAllFieldAndDataMap(Object obj, Map<String, String> map) {
List<String> fnList = getAllFields(obj);
for (int i = 0; i < fnList.size(); i++) {
Object o = invokeGetterMethod(obj, fnList.get(i));
if (o instanceof String) {
map.put(fnList.get(i), (String) o);
} else if (o instanceof Date) {
map.put(fnList.get(i), DateUtil.convertDateFormat((Date) o, "yyyy-MM-dd HH:mm:ss"));
} else {
map.put(fnList.get(i), ConvertUtils.convert(o));
}
}
return map;
}
/**
* 获得当前对象的所有字段
* Jun 19, 2012 9:44:47 AM
* @param obj
* @return
*/
public static List<String> getAllFields(Object obj) {
List<String> filedNameList = new ArrayList<String>();
Class<?> cls = obj.getClass();// 当前类型
Field[] fs = cls.getDeclaredFields();// 当前类型的所有字段
for (int i = 0; i < fs.length; i++) {
String filedName = fs[i].getName();
if (!"serialVersionUID".equals(filedName)) {
filedNameList.add(filedName);
}
}
return filedNameList;
}
/**
* 调用Getter方法.
*/
public static Object invokeGetterMethod(Object target, String propertyName) {
String getterMethodName = "get" + StringUtils.capitalize(propertyName);
return invokeMethod(target, getterMethodName, new Class[] {}, new Object[] {});
}
/**
* 直接调用对象方法, 无视private/protected修饰符.
*/
public static Object invokeMethod(final Object object, final String methodName, final Class<?>[] parameterTypes, final Object[] parameters) {
Method method = getDeclaredMethod(object, methodName, parameterTypes);
if (method == null) {
throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + object + "]");
}
method.setAccessible(true);
try {
return method.invoke(object, parameters);
} catch (Exception e) {
throw convertReflectionExceptionToUnchecked(e);
}
}
/**
* 循环向上转型, 获取对象的DeclaredMethod.
*
* 如向上转型到Object仍无法找到, 返回null.
*/
protected static Method getDeclaredMethod(Object object, String methodName, Class<?>[] parameterTypes) {
// Assert.notNull(object, "object不能为空");
for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
try {
return superClass.getDeclaredMethod(methodName, parameterTypes);
} catch (NoSuchMethodException e) {// NOSONAR
// Method不在当前类定义,继续向上转型
}
}
return null;
}
/**
* 将反射时的checked exception转换为unchecked exception.
*/
public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) {
return convertReflectionExceptionToUnchecked(null, e);
}
public static RuntimeException convertReflectionExceptionToUnchecked(String desc, Exception e) {
desc = (desc == null) ? "Unexpected Checked Exception." : desc;
if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException || e instanceof NoSuchMethodException) {
return new IllegalArgumentException(desc, e);
} else if (e instanceof InvocationTargetException) {
return new RuntimeException(desc, ((InvocationTargetException) e).getTargetException());
} else if (e instanceof RuntimeException) {
return (RuntimeException) e;
}
return new RuntimeException(desc, e);
}
}