⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 copyutil.java

📁 本公司开发项目中本人做的公共类文件。如文件的操作
💻 JAVA
字号:
package com.intohotel.util;

import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.ResourceBundle;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Hibernate;

import com.intohotel.exception.CopyException;

public class CopyUtil {
	private static final Log log = LogFactory.getLog(CopyUtil.class);
	/**
	 * PO转化为VO
	 * 
	 * @param dest
	 * @param orig
	 * @return the dest bean
	 * @throws CopyException
	 */
	@SuppressWarnings("unchecked")
	private static Object copyProperties(Object dest, Object orig,int lays)
			throws CopyException {
		if (dest == null || orig == null) {
			return dest;
		}
		if(!Hibernate.isInitialized(orig)){
			Hibernate.initialize(orig);
		}
		lays++;
		if(log.isDebugEnabled()){
			log.debug("第"+lays+"级对象,开始COPY:"+dest.getClass().getName());
		}
		PropertyDescriptor[] destDesc = PropertyUtils
				.getPropertyDescriptors(dest);
		try {
			for (int i = 0; i < destDesc.length; i++) {
				Class destType = destDesc[i].getPropertyType();
				Class origType = PropertyUtils.getPropertyType(orig,
						destDesc[i].getName());
				if (destType != null && destType.equals(origType)
						&& !destType.equals(Class.class)) {
					if (!Collection.class.isAssignableFrom(origType)) {
						try {
							if(PropertyUtils.isWriteable(dest, destDesc[i].getName())){
								Object value = PropertyUtils.getProperty(orig,
										destDesc[i].getName());	
								if(!Hibernate.isInitialized(value)){
									if(log.isDebugEnabled()){
										log.debug("第"+lays+"级对象,属性"+origType.getSimpleName()+"."+destDesc[i].getName()+" 被Hibernate.initialize");
									}
									Hibernate.initialize(value);
								}
								if(log.isDebugEnabled()){
									log.debug("第"+lays+"级对象,属性"+destDesc[i].getName()+"="+value);
								}
								PropertyUtils.setProperty(dest, destDesc[i]
										.getName(), value);
							}
						} catch (Exception ex) {
							if(log.isWarnEnabled())
								log.warn("第"+lays+"级对象,出错:", ex);
						}
					}
				}else{
					try{
						if(PropertyUtils.isWriteable(dest, destDesc[i].getName())){
							Collection value = (Collection) PropertyUtils.getProperty(orig,
									destDesc[i].getName());	
							if(log.isDebugEnabled()){
								log.debug("第"+lays+"级对象,属性"+destDesc[i].getName()+"是Collection");
							}
							if(value!=null){
								if(!Hibernate.isInitialized(value)){
									Hibernate.initialize(value);
								}
								java.util.Iterator it = value.iterator();
								Collection<Object> coll = new HashSet<Object>();
								while(it.hasNext()){
									Object subValue = it.next();
									if(subValue!=null){
										Object newSubValue = subValue.getClass().newInstance();
										copyProperties(newSubValue,subValue,lays);
										coll.add(newSubValue);
									}
								}
								PropertyUtils.setProperty(dest, destDesc[i].getName(), coll);
							}
						}
					}catch(Exception e){
						if(log.isWarnEnabled())
							log.warn("第"+lays+"级Collection对象,出错:", e);
					}
					
				}
			}
			if(log.isDebugEnabled()){
				log.debug("完成"+dest.getClass().getName()+"COPY");
			}
			return dest;
		} catch (Exception ex) {
			log.equals(ex);
			throw new CopyException(ex);
		}
	}
	/**
	 * PO/VO对象转化,无过滤参数
	 * @param newObj
	 * 		新对象,即被转化目标对象VO
	 * @param oldObj
	 * 		旧对象,即被转化对象PO
	 * @return
	 * @throws CopyException
	 */
	public static Object copyProperties(Object newObj, Object oldObj
			) throws CopyException{
		return copyProperties(newObj,oldObj,0);
	}
	
	/**
	 * PO/VO对象转化,可以通过className进行滤过<br>
	 * className是属性文件名,OrderBill.properties<br>
	 * 内容example:<br>
	 * name=false<br>
	 * <b>name是OrderBill里的字段,即对应的setter/getter,上述所设,即name中的成不传递到newObj中的name里去</b><br>
	 * agrPriBills.uuid=false<br>
	 * <b>如果有"."表示是Collection对象,上述设置是agrPriBills收集中的对象中的uuid不传递到newObj中的agrPriBills收集中的对象uuid对应的域"field"里去。</b><br>
	 * @param newObj
	 * 		新对象,即被转化目标对象VO
	 * @param oldObj
	 * 		旧对象,即被转化对象PO
	 * @param className
	 * 		className是以className为文件名的属性文件,存放于resource包下,定义了不需要传值的字段。
	 * @return
	 * @throws CopyException
	 */
	public static Object copyProperties(Object newObj, Object oldObj,
			String className) throws CopyException{
		return copyProperties(newObj,oldObj,className,0);
	}

	/**
	 * PO到VO转化时,允许过滤 Exception the Entity and Collection Type
	 * 
	 * @param dest
	 * @param orig
	 * @param ignores
	 * @return the dest bean
	 * @throws CopyException
	 */
	@SuppressWarnings("unchecked")
	private static Object copyProperties(Object dest, Object orig,
			String className,int lays) throws CopyException {
		if (dest == null || orig == null) {
			return dest;
		}
		if(!Hibernate.isInitialized(orig)){
			Hibernate.initialize(orig);
		}
		Map<String,String> ignores = getIgnores(className);
		String curProp = "";
		if(className.indexOf(".")>0){
			curProp = className.substring(className.indexOf(".")+1)+".";
		}
		lays++;
		if(log.isDebugEnabled()){
			
			log.debug("第"+lays+"级对象,开始COPY:"+dest.getClass().getName());
		}
		PropertyDescriptor[] destDesc = PropertyUtils
				.getPropertyDescriptors(dest);
		try {
			for (int i = 0; i < destDesc.length; i++) {
				if (contains(ignores, curProp+destDesc[i].getName())) {
					if(log.isDebugEnabled()){
						log.debug("第"+lays+"级对象,当前属性值:"+curProp+destDesc[i].getName());
						log.debug("第"+lays+"级对象,忽略"+className+"."+ destDesc[i].getName());
					}
					continue;
				}
				Class destType = destDesc[i].getPropertyType();
				Class origType = PropertyUtils.getPropertyType(orig,
						destDesc[i].getName());
				if (destType != null && destType.equals(origType)
						&& !destType.equals(Class.class)) {
					if (!Collection.class.isAssignableFrom(origType) ) {
						try{
//							if(getIgnores(destType.getSimpleName())!=null){
//								Object value = PropertyUtils.getProperty(orig,
//										destDesc[i].getName());
//								if(log.isDebugEnabled()){
//									log.debug("第"+lays+"级对象,属性"+className+"."+destDesc[i].getName()+" 是持久对象");
//								}
//								if(value!=null){
//									Object newSubValue = value.getClass().newInstance();
//									copyProperties(newSubValue,value,className+"."+destDesc[i].getName(),lays);		
//									PropertyUtils.setProperty(dest, destDesc[i].getName(),
//											newSubValue);
//								}
//							}else{//暂时不考虑是对象的COPY,只对Collection对象进行相应过滤
							if(PropertyUtils.isWriteable(dest, destDesc[i].getName())){
									Object value = PropertyUtils.getProperty(orig,
											destDesc[i].getName());
									if(!Hibernate.isInitialized(value)){
										if(log.isDebugEnabled()){
											log.debug("第"+lays+"级对象,属性"+className+"."+destDesc[i].getName()+" 被Hibernate.initialize");
										}
										Hibernate.initialize(value);
									}
									if(log.isDebugEnabled()){
										log.debug("第"+lays+"级对象,属性"+className+"."+destDesc[i].getName()+"="+value);
									}
									PropertyUtils.setProperty(dest, destDesc[i].getName(),
											value);
							}
//							}
						}catch(Exception e){
							if(log.isWarnEnabled())
								log.warn("第"+lays+"级对象,出错:", e);
						}
					}else{
						try{
							if(PropertyUtils.isWriteable(dest, destDesc[i].getName())){
								Collection value = (Collection) PropertyUtils.getProperty(orig,
										destDesc[i].getName());	
								if(log.isDebugEnabled()){
									log.debug("第"+lays+"级对象,属性"+className+"."+destDesc[i].getName()+"是Collection");
								}
								if(value!=null){
									if(!Hibernate.isInitialized(value)){
										Hibernate.initialize(value);
									}
									java.util.Iterator it = value.iterator();
									Collection<Object> coll = new HashSet<Object>();
									while(it.hasNext()){
										Object subValue = it.next();
										if(subValue!=null){
											Object newSubValue = subValue.getClass().newInstance();
											copyProperties(newSubValue,subValue,className+"."+destDesc[i].getName(),lays);
											coll.add(newSubValue);
										}
									}
									PropertyUtils.setProperty(dest, destDesc[i].getName(), coll);
								}
							}
						}catch(Exception e){
							if(log.isWarnEnabled())
								log.warn("第"+lays+"级Collection对象,出错:", e);
						}
					}
				}
			}
			return dest;
		} catch (Exception ex) {
			if(log.isWarnEnabled())
				log.warn("第"+lays+"级对象,出错:", ex);
			throw new CopyException(ex);
		}
	}

	static boolean contains(String className,String propName){
		return contains(getIgnores(className),propName);
	}
	static boolean contains(Map<String,String> ignores, String name) {
		if(ignores==null)
			return false;
		if(ignores.containsKey(name) && "false".equalsIgnoreCase(ignores.get(name))){
			return true;			
		}
		return false;
	}
	//定义全局的PO转VO规则
	private static Map<String,Map<String,String>> DTORULES = new HashMap<String, Map<String,String>>();
	
	/**
	 * 获取PO转VO规则,如果全属没找到则到属性文件中去找,并且把找到的放到DTORULES中去
	 * @param className
	 * @return
	 */
	private static Map<String,String> getIgnores(String className){
		String header = className;
		if(header.indexOf(".")>0)
			header = header.substring(0,header.indexOf("."));
		if(log.isDebugEnabled()){
			log.debug("一级对象为:"+header);
			log.debug("当前对象为:"+className);
		}
		if(DTORULES!=null && DTORULES.get(header)!=null)
			return DTORULES.get(header);
		try{
			ResourceBundle prop = ResourceBundle.getBundle("resource/"+header);
			Map<String,String> rules = new HashMap<String, String>();
			Enumeration<String> en = prop.getKeys();
			while(en.hasMoreElements()){
				String key = en.nextElement();
				rules.put(key.trim(), prop.getString(key).trim());
			}
			DTORULES.put(header, rules);
			return rules;
		}catch(Exception e){
			if(log.isErrorEnabled()){
				log.error("不能读取属性文件",e);
			}
			return null;
		}
	}
	
	
	
	/**
	 * 拷贝orig对象中不为collection对象的属性到dest
	 * @param dest
	 * @param orig
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws NoSuchMethodException
	 */
	public static void copyPropertiesExceptCollection(Object dest,Object orig) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException{
		PropertyUtils.copyProperties(dest, orig);
		PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(orig);
		for (PropertyDescriptor pd : pds) {
			if(Collection.class.isAssignableFrom(pd.getPropertyType()) && PropertyUtils.isWriteable(dest, pd.getName())){
				BeanUtils.setProperty(dest, pd.getName(), null);
			}else{
				
//				Object objs = BeanUtils.
				
			}
		}
	}
	
	/**
	 * 更新数据部分字段
	 * 将orig对象中value不为null的属性更新到dest对象中(不包括Collection对象)
	 * @param dest
	 * @param orig
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws NoSuchMethodException
	 */
	public static void updateProperties(Class<?> clazz,Object dest,Object orig) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException{
		PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(clazz);
		if(pds.length == 0)
			log.debug("PropertyDescriptor[] pds size 0" );
		for(PropertyDescriptor pd : pds){
			if(PropertyUtils.getProperty(orig, pd.getName()) != null
					&& PropertyUtils.isWriteable(dest, pd.getName())
					&& PropertyUtils.isReadable(orig, pd.getName())
					&& !Collection.class.isAssignableFrom(pd.getPropertyType())){
				PropertyUtils.setProperty(dest, pd.getName(), PropertyUtils.getProperty(orig, pd.getName()));
				if(log.isDebugEnabled()){
					log.debug("[已更新]Property:"+pd.getName()+"("+pd.getPropertyType().getName()+"),dest.isWriteable:"+PropertyUtils.isWriteable(dest, pd.getName())+", orig.isReadable:"+PropertyUtils.isReadable(orig, pd.getName()));
				}
			}else{
				if(log.isDebugEnabled()){
					log.debug("Property:"+pd.getName()+"("+pd.getPropertyType().getName()+"),dest.isWriteable:"+PropertyUtils.isWriteable(dest, pd.getName())+", orig.isReadable:"+PropertyUtils.isReadable(orig, pd.getName()));
				}
			}
		}
	}
	
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -