java type对象转class对象_关于定义ObjectConvertorUtils实体对象转换工具类对POJO及DTO传值对象间通过其class或对象情况相互转换处理...

一、前言

基于java.lang.reflect.*反射机制定义对象转换工具类,实现POJO持久化实体和DTO传值对象间相互转换 - 单对象通过源对象及目标class类进行pojoDtoConvertor相互转换(POJODTO)、集合对象转换通过源对象序列及目标class类进行pojoDtoCollectionConvertor相互转换(List List)、源对象和目标对象pojoDtoConvertor相互转换(POJODTO)。

二、代码示例import java.lang.reflect.Field;@b@import java.lang.reflect.InvocationTargetException;@b@import java.lang.reflect.Method;@b@import java.math.BigDecimal;@b@import java.util.ArrayList;@b@import java.util.Date;@b@import java.util.List; @b@import org.apache.log4j.Logger; @b@import com.xwood.common.util.date.DateUtils;@b@@b@/**@b@ * 类描述: 近似类(e.g. POJO vs DTO ) 存在多个同名属性,本类为从源对象生成目标对象提供便利@b@ * 注:目前只对同名属性进行赋值,非同名属性忽略,请自行对应@b@ * 

当源对象或目标对象未找到属性时,会获取直接父类的属性

 @b@ */@b@public abstract class ObjectConvertorUtils {@b@@b@protected static final Logger log = Logger.getLogger(ObjectConvertorUtils.class);@b@@b@/**@b@ * 单对象转换(e.g.POJODTO)@b@ *  需要有get/set方法 @b@ * @param @b@ * @param source 源对象@b@ * @param dest 目标类@b@ * @param idForce 是否强制同步非同类型的同名属性(只支持基本数据类型)@b@ * @return 目标类的一个实例@b@ */@b@public static  T pojoDtoConvertor(Object source, Class dest, boolean isForce) {@b@if(source == null){@b@return null;@b@}@b@@b@try {@b@T dto = dest.newInstance();@b@Field[] fields = dest.getDeclaredFields();@b@@b@Field[] totalFields = null;@b@@b@//直接父类@b@Class> superClass = dest.getSuperclass();@b@if(superClass != null){@b@Field[] superFields =superClass.getDeclaredFields();@b@totalFields = new Field[fields.length + superFields.length];@b@@b@for(int j = 0; j  0) {@b@for (Field field : totalFields) {@b@String fieldName = field.getName();@b@String getMethodName = "get"@b@+ fieldName.substring(0, 1).toUpperCase()@b@+ fieldName.substring(1);@b@String setMethodName = "set"@b@+ fieldName.substring(0, 1).toUpperCase()@b@+ fieldName.substring(1);@b@@b@Method getMethod;@b@try {@b@getMethod = source.getClass().getMethod(getMethodName,@b@new Class[] {});@b@} catch (NoSuchMethodException e) {@b@log.warn(" class: " + source.getClass() + " do not have Method: " + getMethodName);@b@continue;@b@}@b@@b@Method setMethod;@b@try {@b@setMethod = dest.getMethod(setMethodName,@b@new Class[] { field.getType() });@b@} catch (NoSuchMethodException e) {@b@log.warn(" class: " + dest + " do not have Method: " + setMethodName);@b@continue;@b@}@b@Object obj = getMethod.invoke(source);@b@@b@if(obj != null){@b@try {@b@Field sourceField = source.getClass().getDeclaredField(field.getName());@b@if(field.getType().isAssignableFrom(sourceField.getType()))@b@setMethod.invoke(dto, new Object[] { obj });@b@else if(isForce){@b@//两边类型都是简单类型及其封装类或String类型时才做强制转换@b@if ((ClassUtils.isPrimitiveOrWrapper(field.getType())@b@|| field.getType().getSimpleName().equals(@b@"String")@b@|| field.getType().getSimpleName().equals(@b@"BigDecimal"))@b@&&@b@((ClassUtils.isPrimitiveOrWrapper(sourceField.getType())@b@|| sourceField.getType().getSimpleName().equals(@b@"String")@b@|| field.getType().getSimpleName().equals(@b@"BigDecimal")))){@b@field.setAccessible(true);@b@setValue(dto, field, obj);@b@}@b@}@b@}  catch (NoSuchFieldException e) {@b@log.warn("classs: " + source.getClass() + " do not have field: " + field.getName());@b@try {@b@Class> sc = source.getClass().getSuperclass();@b@if(sc != null){@b@Field sourceField = sc.getDeclaredField(field.getName());@b@if(field.getType().isAssignableFrom(sourceField.getType()))@b@setMethod.invoke(dto, new Object[] { obj });@b@else if(isForce){@b@//两边类型都是简单类型及其封装类或String类型时才做强制转换@b@if ((ClassUtils.isPrimitiveOrWrapper(field.getType())@b@|| field.getType().getSimpleName().equals(@b@"String")@b@|| field.getType().getSimpleName().equals(@b@"BigDecimal"))@b@&&@b@((ClassUtils.isPrimitiveOrWrapper(sourceField.getType())@b@|| sourceField.getType().getSimpleName().equals(@b@"String")@b@|| field.getType().getSimpleName().equals(@b@"BigDecimal")))){@b@field.setAccessible(true);@b@setValue(dto, field, obj);@b@}@b@}@b@}else{@b@continue;@b@}@b@} catch (NoSuchFieldException e1) {@b@log.warn("super classs: " + source.getClass().getSuperclass() + " do not have field: " + field.getName());@b@continue;@b@}@b@}@b@}@b@}@b@}@b@@b@return dto;@b@@b@} catch (InstantiationException e) {@b@log.error(e.toString());@b@} catch (SecurityException e) {@b@log.error(e.toString());@b@} catch (InvocationTargetException e) {@b@log.error(e.toString());@b@} catch (IllegalAccessException e) {@b@log.error(e.toString());@b@} catch (IllegalArgumentException e) {@b@log.error(e.toString());@b@}@b@@b@return null;@b@}@b@@b@private static void setValue(Object obj, Field field, Object value) throws IllegalAccessException{@b@if(value == null){@b@return;@b@}@b@try{@b@field.set(obj, value);@b@}catch(IllegalArgumentException e){@b@field.set(obj, getRealValue(field.getType(),value));@b@}@b@}@b@@b@private static Object getRealValue(Class> type, Object value){@b@if(int.class.isAssignableFrom(type)){@b@return new Integer(value.toString());@b@}else if(long.class.isAssignableFrom(type)){@b@return new Long(value.toString());@b@}else if(boolean.class.isAssignableFrom(type)){@b@return new Boolean(value.toString());@b@}else if(double.class.isAssignableFrom(type)){@b@return new Double(value.toString());@b@}else if(char.class.isAssignableFrom(type)){@b@return (Character) value.toString().charAt(0);@b@}else if(short.class.isAssignableFrom(type)){@b@return new Short(value.toString());@b@}else if(float.class.isAssignableFrom(type)){@b@return new Float(value.toString());@b@}else if(byte.class.isAssignableFrom(type)){@b@return new Byte(value.toString());@b@}else if(BigDecimal.class.isAssignableFrom(type)){@b@return new BigDecimal(value.toString());@b@}@b@if(Date.class.isAssignableFrom(type)){@b@return DateUtils.string2Date(value.toString());@b@}@b@return null;@b@}@b@@b@/**@b@ * 集合对象转换(e.g.List  List)@b@ *  需要有get/set方法 @b@ * @param @b@ * @param source 源对象集合@b@ * @param dest 目标类@b@ * @param isForce 是否强制@b@ * @return@b@ */@b@public static  List pojoDtoCollectionConvertor(List> source, Class dest, boolean isForce) {@b@if(source == null){@b@return null;@b@}@b@List list = new ArrayList();@b@for(Object o : source){@b@if(o == null) continue;@b@T t = pojoDtoConvertor(o, dest, isForce);@b@if( t != null )list.add(t);@b@}@b@return list;@b@}@b@@b@/**@b@ * 对象转换(e.g.POJODTO) @b@ * @param @b@ * @param source 源对象@b@ * @param target 目标对象@b@ */@b@public static void pojoDtoConvertor(Object source, Object target) {@b@if(source == null || target == null){@b@return;@b@}@b@Class> sourceClazz = source.getClass();@b@Class> targetClazz = target.getClass();@b@log.debug("---source object class type is " + sourceClazz.toString());@b@log.debug("---target object class type is " + targetClazz.toString());@b@Field[] fields = sourceClazz.getDeclaredFields();@b@Field targetField;@b@for (Field field : fields) {@b@field.setAccessible(true);@b@try {@b@Object property = field.get(source);@b@targetField = targetClazz.getDeclaredField(field.getName());@b@if (targetField.getType().isAssignableFrom(field.getType())) {@b@if (property != null)@b@log.debug("---copy field " + field.getName()@b@+ ",tareget field " + targetField.toString()@b@+ ",value is " + property.toString());@b@targetField.setAccessible(true);@b@targetField.set(target, property);@b@}@b@} catch (IllegalArgumentException e) {@b@log.error("IllegalArgument " + e);@b@} catch (IllegalAccessException e) {@b@log.error("Illegal Access " + e);@b@} catch (SecurityException e) {@b@e.printStackTrace();@b@} catch (NoSuchFieldException e) {@b@log.debug("---no such field[" + field.getName()@b@+ "] in target object..");@b@continue;@b@}@b@}@b@}@b@@b@}import java.sql.Timestamp;@b@import java.text.DateFormat;@b@import java.text.ParseException;@b@import java.text.SimpleDateFormat;@b@import java.util.ArrayList;@b@import java.util.Calendar;@b@import java.util.Date;@b@import java.util.List;@b@ @b@public class DateUtils {@b@@b@private final static String pattern = "yyyy-MM-dd HH:mm:ss";@b@private final static String forPattern="yyyy-M-d";@b@@b@public static String dateToString(){@b@SimpleDateFormat sdf = new SimpleDateFormat(pattern);@b@return sdf.format(new Date());@b@}@b@@b@/**@b@ * 获得月初@b@ * @param object(转出表)@b@ * @return getFirstDateOfCurMonth@b@ * @throws ParseException @b@ */@b@public static String getFirstDateByCurDate(String date) throws ParseException{@b@Calendar first =stringToCalendar(date);@b@int minDay = first.getMinimum(Calendar.DAY_OF_MONTH);@b@minDay = first.getMinimum(Calendar.DAY_OF_MONTH);@b@first.set(Calendar.DAY_OF_MONTH, minDay);@b@SimpleDateFormat sdf = new SimpleDateFormat(forPattern);@b@return sdf.format(first.getTime());@b@}@b@@b@public static Calendar stringToCalendar(String date) throws ParseException{@b@Calendar calendar = Calendar.getInstance();@b@Date firstDate = null;@b@try {@b@firstDate = DateUtils.stringToDate(date, forPattern);@b@} catch (ParseException e) {@b@e.printStackTrace();@b@}@b@calendar.setTime(firstDate);@b@return calendar;@b@}@b@@b@public static String dateToString(Date object){@b@if(null==object){@b@return null;@b@}@b@SimpleDateFormat sdf = new SimpleDateFormat(pattern);@b@return sdf.format(object);@b@@b@}@b@@b@public static Date stringToDate(String date) throws ParseException{@b@SimpleDateFormat sdf = new SimpleDateFormat(pattern);@b@return sdf.parse(date);@b@}@b@@b@public static Date stringToDate(String date,String pattern) throws ParseException{@b@if(date == null || "".equals(date.trim())||"null".equals(date.trim())){@b@return null;@b@}@b@SimpleDateFormat sdf = new SimpleDateFormat(pattern);@b@return sdf.parse(date);@b@}@b@@b@public static String getStrNowDateHmsMs(){@b@Date tdate = new Date();@b@String nowtime = new Timestamp(tdate.getTime()).toString();@b@int len = nowtime.length();@b@int between = 23-len;@b@for(int i=0;i formats = new ArrayList();@b@   formats.add( new SimpleDateFormat("yyyy-MM-dd") );@b@   formats.add( new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") );@b@   formats.add( new SimpleDateFormat("yy-MM-dd") );@b@   formats.add( new SimpleDateFormat("yy-MM-dd HH:mm:ss") );@b@   formats.add( new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS") );@b@  @b@   formats.add( new SimpleDateFormat("yyyy/MM/dd HH:mm:ss") );@b@   formats.add( new SimpleDateFormat("yyyy/MM/dd") );@b@   formats.add( new SimpleDateFormat("yy/MM/dd") );@b@   formats.add( new SimpleDateFormat("yy/MM/dd HH:mm:ss") );@b@   @b@   @b@   formats.add( new SimpleDateFormat("yyyyMMdd HH:mm:ss") );@b@   formats.add( new SimpleDateFormat("yyyyMMddHHmmss") );@b@   formats.add( new SimpleDateFormat("yyyyMMddHHmm") );@b@   formats.add( new SimpleDateFormat("yyyyMMddHH") );@b@   formats.add( new SimpleDateFormat("yyyyMMdd") );@b@   @b@   formats.add( new SimpleDateFormat("yyyy.MM.dd") );@b@   formats.add( new SimpleDateFormat("yyyy.MM.dd HH:mm:ss") );@b@@b@   formats.add( new SimpleDateFormat("EEE MMM d hh:mm:ss a z yyyy") );@b@   formats.add( new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy") );@b@   @b@   for(DateFormat format:formats){@b@   try {@b@   Date d = format.parse(s);@b@   return d;@b@   } catch (ParseException e) {@b@   }@b@   }@b@   return null;@b@   }@b@   @b@   @b@   /** @b@    * 获得当年1月1日的日期 @b@    */@b@public static String getFirstDayOfYear(String str) {@b@SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");@b@Date date = null;@b@String year = null;@b@try {@b@date = sd.parse(str);@b@Calendar calendar = Calendar.getInstance();@b@calendar.setTime(date);@b@SimpleDateFormat sdf = new SimpleDateFormat("yyyy");@b@year = sdf.format(calendar.getTime());@b@return year + "-01-01 00:00:00";@b@} catch (ParseException e) {@b@e.printStackTrace();@b@}@b@return year;@b@}@b@@b@/**@b@ * 判断时间是否在凌晨19:00:00 ~~23:59:59@b@ */@b@public static boolean is7To12(){@b@Calendar cal = Calendar.getInstance();@b@SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");@b@String c = sdf.format(cal.getTime());@b@Integer time = Integer.parseInt(c.replace(":",""));@b@if(time>=190000 && time <=235959){@b@return true;@b@}@b@return false;@b@}@b@@b@/**@b@ * 判断时间是否在凌晨00:00:00 ~~05:00:00@b@ */@b@public static boolean is0To5(){@b@Calendar cal = Calendar.getInstance();@b@SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");@b@String c = sdf.format(cal.getTime());@b@Integer time = Integer.parseInt(c.replace(":",""));@b@if(time>=1 && time <=50000){@b@return true;@b@}@b@return false;@b@}@b@@b@/**@b@ * 根据传入日期param参数获取前一天日期@b@ * @param param: yyyy-MM-dd HH:mm:ss@b@ */@b@public static String getYesterDay(String param){@b@SimpleDateFormat frt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");@b@try {@b@Date date = frt.parse(param);@b@Calendar cal = Calendar.getInstance();@b@cal.setTime(date);@b@cal.add(Calendar.DATE, -1);@b@return frt.format(cal.getTime());@b@} catch (ParseException e) {@b@e.printStackTrace();@b@}catch(Exception e){@b@e.printStackTrace();@b@}@b@return null;@b@}@b@@b@/**@b@ * 根据传入日期param参数获取35天前的日期@b@ * @param param: yyyy-MM-dd HH:mm:ss@b@ **/@b@public static String getBefore35(String param){@b@SimpleDateFormat frt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");@b@try {@b@Date date = frt.parse(param);@b@Calendar cal = Calendar.getInstance();@b@cal.setTime(date);@b@cal.add(Calendar.DATE, -34);@b@return frt.format(cal.getTime());@b@} catch (ParseException e) {@b@e.printStackTrace();@b@}catch(Exception e){@b@e.printStackTrace();@b@}@b@return null;@b@}@b@@b@/** @b@ * 判断当前日期是否是一周的第一天 @b@ */@b@public static boolean isFirstDayOfWeek() {@b@Calendar cal = Calendar.getInstance();@b@cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);// 这里设置从周一开始,若需要根据系统时区自动获取,则采用下边的方式@b@Calendar cal2 = Calendar.getInstance();@b@return cal.equals(cal2);@b@}@b@@b@/** @b@ * 判断当前日期是否是一月的第一天 @b@ */@b@public static boolean isFirstDayOfMonth() {@b@Calendar cal = Calendar.getInstance();@b@cal.set(Calendar.DAY_OF_MONTH, 1);// 这里设置从周一开始,若需要根据系统时区自动获取,则采用下边的方式@b@Calendar cal2 = Calendar.getInstance();@b@return cal.equals(cal2);@b@}@b@@b@/**@b@ * 当前日期的获得本月1号日期 calendar 当前日期@b@ */@b@public static String getFirstDateOfCurMonth(Calendar calendar) {@b@Calendar first = Calendar.getInstance();@b@first.setTime(calendar.getTime());@b@@b@int minDay = first.getMinimum(Calendar.DAY_OF_MONTH);@b@@b@minDay = first.getMinimum(Calendar.DAY_OF_MONTH);@b@first.set(Calendar.DAY_OF_MONTH, minDay);@b@SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");@b@return sdf.format(first.getTime());@b@}@b@@b@/** @b@ * 获得上个月1号 @b@ */@b@public static Date getFirstDateOfLastMonth(Calendar calendar) {@b@Calendar first = Calendar.getInstance();@b@first.setTime(calendar.getTime());@b@@b@int minDay = first.getMinimum(Calendar.DAY_OF_MONTH);@b@first.add(Calendar.MONTH, -1);@b@@b@minDay = first.getMinimum(Calendar.DAY_OF_MONTH);@b@first.set(Calendar.DAY_OF_MONTH, minDay);@b@return first.getTime();@b@}@b@@b@/** @b@ * 获取上个月最后一天的日期 @b@ */@b@public static Date getLastDateOfLastMonth(Calendar calendar) {@b@Calendar last = Calendar.getInstance();@b@last.setTime(calendar.getTime());@b@@b@int maxDay = last.getMaximum(Calendar.DAY_OF_MONTH);@b@last.add(Calendar.MONTH, -1);@b@@b@maxDay = last.getActualMaximum(Calendar.DAY_OF_MONTH);@b@last.set(Calendar.DAY_OF_MONTH, maxDay);@b@return last.getTime();@b@}@b@@b@/**@b@ * 获取日期所在月的最后一天的日期@b@ * @param calendar@b@ * @return@b@ */@b@public static Date getLastDateOfMonth(Date date)@b@{@b@Calendar last = Calendar.getInstance();@b@last.setTime(date);@b@@b@intmaxDay = last.getActualMaximum(Calendar.DAY_OF_MONTH);@b@last.set(Calendar.DAY_OF_MONTH, maxDay);@b@return last.getTime();@b@@b@}@b@@b@@b@public static String getDateYMD(Date date)@b@{@b@   Calendar c = Calendar.getInstance();@b@   c.setTime(date);@b@String ymd = c.get(Calendar.YEAR)+""+c.get(Calendar.MONTH)+""+c.get(Calendar.DATE);@b@return ymd;@b@}@b@/** @b@ * 获得上周第一天的日期 @b@ */@b@public static Date getFirstDateOfLastWeek(Calendar calendar) {@b@Calendar first = Calendar.getInstance();@b@first.setTime(calendar.getTime());@b@first.setFirstDayOfWeek(Calendar.MONDAY);@b@int index = first.getFirstDayOfWeek();@b@first.set(Calendar.DAY_OF_WEEK, index);@b@first.add(Calendar.DAY_OF_WEEK, -7);@b@return first.getTime();@b@}@b@@b@/** @b@ * 获得上周最后一天的日期 @b@ */@b@public static Date getLastDateOfLastWeek(Calendar calendar) {@b@Calendar last = Calendar.getInstance();@b@last.setTime(calendar.getTime());@b@last.setFirstDayOfWeek(Calendar.MONDAY);@b@int index = last.getFirstDayOfWeek();@b@last.set(Calendar.DAY_OF_WEEK, index);@b@last.add(Calendar.DAY_OF_WEEK, -1);@b@return last.getTime();@b@}@b@@b@/** @b@ * 获得日期date所在的当前周数@b@ */@b@public static String getConvertoWeekDate(String date, String inputFormat)@b@throws ParseException {@b@SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");@b@Date myd = format.parse(date);@b@SimpleDateFormat sdf = new SimpleDateFormat(inputFormat);@b@Calendar ccc = Calendar.getInstance();@b@ccc.setTime(myd);@b@ccc.setFirstDayOfWeek(Calendar.MONDAY);@b@@b@/**/@b@String str = date.substring(0, 4);@b@SimpleDateFormat tempFormat = new SimpleDateFormat("yyyy-MM-dd");@b@Date compara = tempFormat.parse(str + "-01-01");@b@Calendar CalP = Calendar.getInstance();@b@CalP.setTime(compara);@b@int x = CalP.get(Calendar.DAY_OF_WEEK);@b@/**/@b@if (x != 2) {@b@sdf.setCalendar(ccc);@b@String s = sdf.format(ccc.getTime());@b@String s1 = s.substring(0, 4);@b@String s2 = s.substring(4, 6);@b@Integer i = Integer.parseInt(s2);@b@if (i > 1) {@b@i = i - 1;@b@}@b@s2 = i + "";@b@if ((i + "").length() 0){@b@return false;@b@}@b@  }catch  (ParseException e){@b@  e.printStackTrace();@b@  }@b@@b@return true;@b@}@b@@b@/** @b@ * 月份范围-本月的26号到下月的25号 @b@ * 例:201208  2012-08-26~2012-09-25@b@ * @param operDate yyyy-MM-dd@b@ * @param month_flag  yyyyMMdd@b@ * @return@b@ * @throws ParseException @b@ */@b@public static boolean tskfMonthDate(String month_flag) {@b@  try{@b@String firstDateStr=month_flag+"26";@b@Date firstDate=stringToDate(firstDateStr, "yyyyMMdd");@b@Calendar calendar=Calendar.getInstance();@b@calendar.setTime(firstDate);@b@calendar.add(Calendar.MONTH, 1);@b@Date endDate=calendar.getTime();@b@Date tarDate=new Date();@b@if(tarDate.compareTo(firstDate)<0||tarDate.compareTo(endDate)>=0){@b@return false;@b@}@b@  }catch  (ParseException e){@b@  e.printStackTrace();@b@  }@b@@b@return true;@b@}@b@@b@    public static void main(String[] args) throws ParseException {@b@ @b@    System.out.println(dateToString(string2Date("20140210110133"))); @b@@b@}@b@}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值