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

📄 transferobjectfactory.java

📁 一个基于Java的新闻发布系统
💻 JAVA
字号:
/*
 *
 * Title: The ERP System of kelamayi Downhole Company [PMIP]
 *
 * Copyright: Copyright (c) 2004
 *
 * Company: westerasoft Co., Ltd
 *
 * All right reserved.
 *
 * Created on 2004-4-8
 *
 * JDK version used		:1.4.1
 *
 * Modification history:
 *
 */
package com.hope.common.util;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;

import org.apache.log4j.Logger;
/**
 * 实现对象之间属性值的复制功能
 * @author biaoping.yin
 * @version 1.0
 */
public class TransferObjectFactory
{
	private static final Logger log = Logger.getLogger(TransferObjectFactory.class);

	/**
	* Use a HashMap to cache class information for
	* Transfer Object classes
	*/
	private static HashMap classDataInfo = new HashMap();
	/**
	* Create a Transfer Object for the given object. The
	* given object must be an EJB Implementation and have
	* a superclass that acts as the class for the entity's
	* Transfer Object. Only the fields defined in this
	* superclass are copied in to the Transfer Object.
	*/
	public static Serializable createTransferObject(
		Object ejb,
		String whichTOType,
		String completeTOType)
	{

		try
		{
			// Get the class data for the complete
			// Transfer Object type
			ClassData cData = getClassData(completeTOType);
			// Get class data for the requested TO type
			ClassData voCData = getClassData(whichTOType);
			// Create the Transfer Object of the requested
			// Transfer Object type...
			Object whichTO = Class.forName(whichTOType).newInstance();
			// get the TO fields for the requested TO
			// from the ClassData for the requested TO
			Field[] voFields = voCData.arrFields;
			// get all fields for the complete TO
			// from the ClassData for complete TO
			Field[] beanFields = cData.arrFields;
			if (voFields == null
				|| voFields.length == 0
				|| beanFields == null
				|| beanFields.length == 0)
			{
				return (Serializable) createTransferObject(ejb, whichTO);
			}
			// copy the common fields from the complete TO
			// to the fields of the requested TO
			for (int i = 0; i < voFields.length; i++)
			{
				try
				{
					String voFieldName = voFields[i].getName();
					for (int j = 0; j < beanFields.length; j++)
					{
						// if the field names are same, copy value
						if (voFieldName.equals(beanFields[j].getName()))
						{
							// Copy value from matching field
							// from the bean instance into the new
							// Transfer Object created earlier
							voFields[i].set(whichTO, beanFields[j].get(ejb));
							break;
						}
					}
				}
				catch (Exception e)
				{
					// handle exceptions that may be thrown
					// by the reflection methods...
				}
			}
			// return the requested Transfer Object
			return (java.io.Serializable) whichTO;
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
			// Handle all exceptions here...
		}
		return null;
	}
	/**
	 * added by biaoping.yin 2004.5.20
	 * 将一个对象属性复制到另一个对象中,对应属性的名称和类型必须一致
	 * @param completeVO:有属性值的对象
	 * @param whichToVO:空对象
	 * @return
	 */
	public static Object createTransferObject(
		Object completeVO,
		Object whichToVO)
	{
		if (completeVO == null || whichToVO == null)
			return null;
		Method[] wMethods = whichToVO.getClass().getMethods();
		Class cClazz = completeVO.getClass();
		if (wMethods == null || wMethods.length == 0)
		{
			return whichToVO;
		}
		for (int i = 0; i < wMethods.length; i++)
		{
			String wmName = wMethods[i].getName();
			if (!wmName.startsWith("set"))
			{
				continue;
			}
			String wmPrex = wmName.substring(0, 3);
			String wfield = wmName.substring(3);
			Method cMethod = null;
			try
			{
				cMethod =
					cClazz.getMethod(
						ValueObjectUtil.getMethodName(wfield),
						null);
				if(cMethod == null)
				{
					log.info(
						new StringBuffer("warning:[")
							.append(wMethods[i])
							.append("]")
							.append(ValueObjectUtil.getMethodName(wfield))
							.append(" not found in [")
							.append(cClazz)
							.append("]!")
							.toString());
					continue;
				}
				Class retType = cMethod.getReturnType();
				Class paramType = wMethods[i].getParameterTypes()[0];

				if (retType == paramType)
				{
					ValueObjectUtil.invoke(
						whichToVO,
						wMethods[i],
						new Object[] {
							 ValueObjectUtil.invoke(
								completeVO,
								cMethod,
								null)});
					//wMethods[i].invoke(whichToVO,new Object[] {cMethod.invoke(
					//completeVO, null)});
				}
				else
				{
					try
					{
						Object obj =
							ValueObjectUtil.typeCast(
								ValueObjectUtil.invoke(
									completeVO,
									cMethod,
									null),
								retType,
								paramType);
						ValueObjectUtil.invoke(
							whichToVO,
							wMethods[i],
							new Object[] { obj });
					}
					catch (NoSupportTypeCastException e)
					{
						throw e;
						//System.out.println("warning ParamTypeNotMatchException:<" + cMethod + "><" + wMethods[i] + "> return value type not match the param type!" );
					}
					//System.out.println("warning ParamTypeNotMatchException:<" + cMethod + "><" + wMethods[i] + "> return value type not match the param type!" );
				}
			}
			catch (NullPointerException e)
			{
				log.info(
					new StringBuffer("warning NullPointerException:[")
						.append(wMethods[i])
						.append("] not found in [")
						.append(cClazz)
						.append("]!")
						.toString());
				continue;
			}
			catch (NoSuchMethodException e)
			{
				log.info(
					new StringBuffer("warning NoSuchMethodException:[")
						.append(e.getMessage())
						.append("]")
						.toString());
				//e.printStackTrace();
				continue;
			}
			catch (SecurityException securitye)
			{
				log.info(
					new StringBuffer("warning SecurityException:[")
						.append(securitye.getMessage())
						.append("]")
						.toString());
				//securitye.printStackTrace();
				continue;
			}
			catch (NoSupportTypeCastException castException)
			{
				log.info(
					new StringBuffer("warning NoSupportTypeCastException:[")
							 .append(cMethod).append("][")
							 .append(wMethods[i])
							 .append("] return value type not match the param type!")
							 .toString());
				continue;
			}
			catch (NumberFormatException e)
			{
				log.info(
					new StringBuffer("warning NumberFormatException:[")
							 .append(e.getMessage())
							 .append("]")
							 .toString());
				//e.printStackTrace();
				continue;
			}
			catch (IllegalArgumentException e)
			{
				log.info(
					new StringBuffer("warning IllegalArgumentException:[")
							 .append(e.getMessage())
							 .append("]")
							 .toString());
				//e.printStackTrace();
				continue;
			}
			catch (Exception e)
			{
				log.info(
					new StringBuffer("warning Exception:[")
							 .append(e.getMessage())
							 .append("]")
							 .toString());
				//e.printStackTrace();
				continue;
			}
		}
		return whichToVO;
	}
	/**
	* Return a ClassData object that contains the
	* information needed to create
	* a Transfer Object for the given class. This information
	* is only obtained from the
	* class using reflection once, after that it will be
	* obtained from the classDataInfo HashMap.
	*/
	private static ClassData getClassData(String className)
	{
		ClassData cData = (ClassData) classDataInfo.get(className);
		try
		{
			if (cData == null)
			{
				// Get the class of the given object and the
				// Transfer Object to be created
				Field[] arrFields;
				Class ejbTOClass = Class.forName(className);
				// Determine the fields that must be copied
				arrFields = ejbTOClass.getFields();
				cData =
					new ClassData(
						ejbTOClass,
						arrFields,
						ejbTOClass.getMethods());
				classDataInfo.put(className, cData);
			}
		}
		catch (Exception e)
		{
			// handle exceptions here...
		}
		return cData;
	}

	public static void main(String[] args)
	{
		//Logger log = Logger.getLogger(TransferObjectFactory.class);

		log.debug("debug:aaaaa");
		log.info("info:bbbbbbb");
		log.warn("warn:bbbbbbb");
		log.error("error:bbbbbbb");

	}
}
/**
* Inner Class that contains class data for the
* Transfer Object classes
*/
class ClassData
{
	// Transfer Object Class
	public Class clsTransferObject;
	// Transfer Object fields
	public Field[] arrFields;
	//Transfer Object methods
	public Method[] arrMethods;
	// Constructor
	public ClassData(Class cls, Field[] fields, Method[] methods)
	{

		clsTransferObject = cls;
		arrFields = fields;
		arrMethods = methods;
	}
}

⌨️ 快捷键说明

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