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

📄 propertyutil.java

📁 javaEE 原代码 javaEE 原代码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
package com;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 通过类反射进行对象与对象之间、对象与request中传递的参数之间的值拷贝。 使用规则: 1)对象与对象之间的值拷贝,对象的属性名称必须相同,大小写敏感。
 * 2)对象与request中参数之间的值拷贝,对象的属性名称必须与参数名称相同。 3)支持String 跟
 * long,double,Date数据类型的自动转换。
 * <p>
 * 2005-10-29 <br>
 * 增加 Long,Double,Short,short 类型的数据与 String类型的转换,增加 Long与long , Double与double ,
 * Short与short的类型转换。 修改bug 无法拷贝对象super class的field的值
 * 
 * 
 * 
 * 
 * @author migro
 * @version v 1.0 $ 2005-10-22 20:47:44 $
 */
public class PropertyUtil {
	private static final String TYPE_STRING = "java.lang.String";

	private static final String TYPE_LONG = "long";

	private static final String TYPE_LONG_OBJ = "java.lang.Long";

	private static final String TYPE_DOUBLE = "double";

	private static final String TYPE_DOUBLE_OBJ = "java.lang.Double";

	private static final String TYPE_DATE = "java.util.Date";

	private static final String TYPE_SET = "java.util.Set";

	private static final String TYPE_HASHSET = "java.util.HashSet";

	private static final String TYPE_SHORT = "short";

	private static final String TYPE_SHORT_OBJ = "java.lang.Short";
	private Date start = new Date();

	public PropertyUtil() {
	}

	/**
	 * 对象之间拷贝相同名称属性的值
	 * 
	 * @param target
	 *            目标对象
	 * @param source
	 *            源对象
	 * @throws SysException
	 */
	public void copy(Object target, Object source) throws SysException {
		Class cTar = target.getClass();
		Class cSou = source.getClass();

		Class[] paramType = new Class[1];
		Object[] paramValue = new Object[1];

		Field[] fTar = getExtendsFields(cTar);// cTar.getDeclaredFields();
		Field[] fSou = getExtendsFields(cSou);// cSou.getDeclaredFields();

		String fNameTar = null; // target field name
		String fTypeTar = null; // target field type
		String fNameSou = null; // source field name
		String fTypeSou = null; // source field type

		Method setMethod = null;
		Object tmpVal = null;

		try {
			for (int i = 0; i < fSou.length; i++) {
				fNameSou = fSou[i].getName();
				fTypeSou = fSou[i].getType().getName();

				for (int j = 0; j < fTar.length; j++) {
					fNameTar = fTar[j].getName();
					fTypeTar = fTar[j].getType().getName();

					/** find the same field , copy value */
					if (fNameSou.equals(fNameTar)) {
						/** set the target obj setXXX() method parameter type */
						paramType[0] = fTar[j].getType();

						/** get the property value from source obj */
						tmpVal = getPropertyValue(fNameSou, null, null, source);

						if (fTypeSou.equals(fTypeTar)) { // the same type
							paramValue[0] = tmpVal;
						} else { // need type convert
							paramValue[0] = objTypeConvert(fTypeTar, fTypeSou,
									tmpVal);
						}

						/** get the setXXX() method from target obj */
						setMethod = cTar.getMethod(getSetMethodName(fNameTar),
								paramType);

						/** invoker the setXXX() method,complete property copy */
						setMethod.invoke(target, paramValue);

						break;
					}
				}
			}
		} catch (NoSuchMethodException e) {
			throw new SysException("SYS-0014", "SYS", "网络繁忙,请稍后再试!", this
					.getClass().getName()
					+ ":objectToObject()", null, e, "值对象缺少基本方法:" + fNameTar);
		} catch (InvocationTargetException e) {
			throw new SysException("SYS-0015", "SYS", "网络繁忙,请稍后再试!", this
					.getClass().getName()
					+ ":objectToObject()", null, e);
		} catch (IllegalAccessException e) {
			throw new SysException("SYS-0016", "SYS", "网络繁忙,请稍后再试!", this
					.getClass().getName()
					+ ":objectToObject()", null, e);
		} catch (NullPointerException upe) {

			throw upe;
		}
	}

	/**
	 * 从Httprequest对象中获得对象中变量的值
	 * 
	 * @param target
	 *            目标对象
	 * @param httpRequest
	 *            JSP、Servlet中的请求对象
	 * @throws SysException
	 */
	public List copyXml(Object target, HttpServletRequest httpRequest)
			throws SysException {
		CDataSet cDataSet = new CDataSet();
		cDataSet.getDataSet(httpRequest);
		List ret = new ArrayList();
		Class cTar = target.getClass();
		Class[] paramType = new Class[1];
		Object[] paramValue = new Object[1];

		Field[] fTar = getExtendsFields(cTar);// cTar.getDeclaredFields();

		String fNameTar = null; // target field name
		String fTypeTar = null; // target field type

		Method setMethod = null;
		Object tmpVal = null;

		try {
			Document doc = cDataSet.getDoc();

			NodeList nodes = doc.getElementsByTagName(getClassName(cTar));
			if (nodes != null) {
				for (int i = 0; i < nodes.getLength(); i++) {
					for (int j = 0; j < fTar.length; j++) {
						fNameTar = fTar[j].getName();
						fTypeTar = fTar[j].getType().getName();

						/** find the value from http request */
						/** set the target obj setXXX() method parameter type */
						paramType[0] = fTar[j].getType();

						/** get the property value from http request */
						NodeList fileds = doc.getElementsByTagName(fNameTar);
						tmpVal = null;
						if (fileds != null && fileds.item(i) != null
								&& fileds.item(i).getFirstChild() != null) {
							tmpVal = fileds.item(i).getFirstChild()
									.getNodeValue();
						}

						if (tmpVal != null) {
							if (fTypeTar.equals("java.lang.String")) {
								paramValue[0] = tmpVal;
							} else { // need type convert
								paramValue[0] = objTypeConvert(fTypeTar,
										"java.lang.String", tmpVal);
							}

							/** get the setXXX() method from target obj */
							setMethod = cTar.getMethod(
									getSetMethodName(fNameTar), paramType);

							/**
							 * invoker the setXXX() method,complete property
							 * copy
							 */
							setMethod.invoke(target, paramValue);
						}
					}
					ret.add(target);
					this.toString(target);
				}
			}

		} catch (NoSuchMethodException e) {
			throw new SysException("SYS-0014", "SYS", "网络繁忙,请稍后再试!", this
					.getClass().getName()
					+ ":requestToObject()", null, e, "值对象缺少基本方法:" + fNameTar);
		} catch (InvocationTargetException e) {
			throw new SysException("SYS-0015", "SYS", "网络繁忙,请稍后再试!", this
					.getClass().getName()
					+ ":requestToObject()", null, e, "property<" + fNameTar
					+ "> value<" + tmpVal + ">");
		} catch (IllegalAccessException e) {
			throw new SysException("SYS-0016", "SYS", "网络繁忙,请稍后再试!", this
					.getClass().getName()
					+ ":requestToObject()", null, e);
		} catch (NullPointerException upe) {

			throw upe;
		}
		long tmp = new Date().getTime() - start.getTime();
		System.out.println("dom耗时:" + tmp + " ms");
		return ret;
	}

	/**
	 * 从Httprequest对象中获得对象中变量的值
	 * 
	 * @param target
	 *            目标对象
	 * @param httpRequest
	 *            JSP、Servlet中的请求对象
	 * @throws SysException
	 */
	public void copy(Object target, HttpServletRequest httpRequest)
			throws SysException {
		Class cTar = target.getClass();

		Class[] paramType = new Class[1];
		Object[] paramValue = new Object[1];

		Field[] fTar = getExtendsFields(cTar);// cTar.getDeclaredFields();

		String fNameTar = null; // target field name
		String fTypeTar = null; // target field type

		Method setMethod = null;
		Object tmpVal = null;

		try {
			for (int j = 0; j < fTar.length; j++) {
				fNameTar = fTar[j].getName();
				fTypeTar = fTar[j].getType().getName();

				/** find the value from http request */
				/** set the target obj setXXX() method parameter type */
				paramType[0] = fTar[j].getType();

				/** get the property value from http request */
				tmpVal = httpRequest.getParameter(fNameTar);

				if (tmpVal != null) {
					if (fTypeTar.equals("java.lang.String")) { // the same type
						paramValue[0] = tmpVal;
					} else { // need type convert
						paramValue[0] = objTypeConvert(fTypeTar,
								"java.lang.String", tmpVal);
					}

					/** get the setXXX() method from target obj */
					setMethod = cTar.getMethod(getSetMethodName(fNameTar),
							paramType);

					/** invoker the setXXX() method,complete property copy */
					setMethod.invoke(target, paramValue);
				}
			}
		} catch (NoSuchMethodException e) {
			throw new SysException("SYS-0014", "SYS", "网络繁忙,请稍后再试!", this
					.getClass().getName()
					+ ":requestToObject()", null, e, "值对象缺少基本方法:" + fNameTar);
		} catch (InvocationTargetException e) {
			throw new SysException("SYS-0015", "SYS", "网络繁忙,请稍后再试!", this
					.getClass().getName()
					+ ":requestToObject()", null, e, "property<" + fNameTar
					+ "> value<" + tmpVal + ">");
		} catch (IllegalAccessException e) {
			throw new SysException("SYS-0016", "SYS", "网络繁忙,请稍后再试!", this
					.getClass().getName()
					+ ":requestToObject()", null, e);
		} catch (NullPointerException upe) {

			throw upe;
		}
	}

	/**
	 * 从数据集ResultSet对象中获得对象中变量的值
	 * 
	 * @param target目标对象
	 * @param res数据集对象
	 * @throws SysException
	 */
	public void copy(Object target, ResultSet res) throws SysException {
		Class cTar = target.getClass();

		Class[] paramType = new Class[1];
		Object[] paramValue = new Object[1];

		Field[] fTar = getExtendsFields(cTar);// cTar.getDeclaredFields();

		String fNameTar = null; // target field name
		String fTypeTar = null; // target field type

		Method setMethod = null;
		String tmpVal = null;

		try {
			for (int j = 0; j < fTar.length; j++) {
				fNameTar = fTar[j].getName();
				fTypeTar = fTar[j].getType().getName();

				/** find the value from http request */
				/** set the target obj setXXX() method parameter type */
				paramType[0] = fTar[j].getType();

				/** get the property value from ResultSet */
				try {
					tmpVal = res.getString(fNameTar);
				} catch (SQLException sss) {
					// ignore SQLExceptions
					tmpVal = null;

				}
				if (tmpVal != null) {
					tmpVal = tmpVal.trim();
				}

				if ((tmpVal != null) && (tmpVal.length() > 0)) {
					if (fTypeTar.equals("java.lang.String")) { // the same type
						paramValue[0] = tmpVal;
					} else { // need type convert
						paramValue[0] = objTypeConvert(fTypeTar,
								"java.lang.String", tmpVal);
					}

					/** get the setXXX() method from target obj */
					setMethod = cTar.getMethod(getSetMethodName(fNameTar),
							paramType);

					/** invoker the setXXX() method,complete property copy */
					setMethod.invoke(target, paramValue);
				}
			}
		} catch (NoSuchMethodException e) {
			throw new SysException("SYS-0014", "SYS", "网络繁忙,请稍后再试!", this
					.getClass().getName()
					+ ":requestToObject()", null, e, "值对象缺少基本方法:" + fNameTar);
		} catch (InvocationTargetException e) {
			throw new SysException("SYS-0015", "SYS", "网络繁忙,请稍后再试!", this
					.getClass().getName()
					+ ":requestToObject()", null, e, "property<" + fNameTar
					+ "> value<" + tmpVal + ">");
		} catch (IllegalAccessException e) {
			throw new SysException("SYS-0016", "SYS", "网络繁忙,请稍后再试!", this
					.getClass().getName()
					+ ":requestToObject()", null, e);
		} catch (NullPointerException upe) {

			throw upe;
		}
	}

	private Object getPropertyValue(String fieldName, Class[] types,
			Object[] params, Object obj) throws NoSuchMethodException,
			InvocationTargetException, IllegalAccessException {
		Object ret = null;

		Class c = obj.getClass();
		Method getMethod = c.getMethod(getGetMethodName(fieldName), types);
		ret = getMethod.invoke(obj, params);

		// System.out.println(getMethod.getName());
		return ret;
	}

	private String getGetMethodName(String fieldName) {
		if (fieldName == null) {
			return null;
		}

		StringBuffer ret = new StringBuffer();
		ret.append("get");
		ret.append(fieldName.substring(0, 1).toUpperCase());
		ret.append(fieldName.substring(1));

		return ret.toString();
	}

	private String getSetMethodName(String fieldName) {
		if (fieldName == null) {
			return null;
		}

		StringBuffer ret = new StringBuffer();
		ret.append("set");
		ret.append(fieldName.substring(0, 1).toUpperCase());
		ret.append(fieldName.substring(1));

		return ret.toString();
	}

	private Object objTypeConvert(String targetType, String sourceType,
			Object obj) throws SysException {
		Object ret = null;
		boolean exception = false;

		try {
			if (targetType.equals(TYPE_STRING)) { // convert to String

				if (obj != null) {
					if (sourceType.equals(TYPE_DATE)
							|| sourceType.equals(TYPE_DOUBLE)
							|| sourceType.equals(TYPE_LONG)
							|| sourceType.equals(TYPE_SHORT)
							|| sourceType.equals(TYPE_LONG_OBJ)
							|| sourceType.equals(TYPE_DOUBLE_OBJ)
							|| sourceType.equals(TYPE_SHORT_OBJ)) {
						ret = formatString(obj);
					} else {
						exception = true;
					}
				} else {
					ret = null;
				}
			} else if (targetType.equals(TYPE_DOUBLE)) { // convert to double

				if (sourceType.equals(TYPE_STRING)) {
					String tmp = (String) obj;

					if ((tmp == null) || (tmp.length() < 1)) {
						tmp = "0.0";
					}

					ret = new Double(tmp);
				} else if (sourceType.equals(TYPE_DOUBLE_OBJ)) {
					ret = obj;
				} else {
					exception = true;
				}
			} else if (targetType.equals(TYPE_LONG)) { // convert to long

				if (sourceType.equals(TYPE_STRING)) {
					String tmp = (String) obj;

					if ((tmp == null) || (tmp.length() < 1)) {
						tmp = "0";
					}

					ret = new Long(tmp);
				} else if (sourceType.equals(TYPE_LONG_OBJ)) {
					ret = obj;
				} else {
					exception = true;
				}
			} else if (targetType.equals(TYPE_DATE)) { // convert to Date

				if (sourceType.equals(TYPE_STRING)) {
					String tmp = (String) obj;

					if ((tmp == null) || (tmp.length() < 1)) {
						ret = null;
					} else {
						ret = DateUtil.parseDate(tmp);
					}
				} else {
					exception = true;
				}
			} else if (targetType.equals(TYPE_SHORT)) { // convert to short

				if (sourceType.equals(TYPE_STRING)) {
					String tmp = (String) obj;

					if ((tmp == null) || (tmp.length() < 1)) {
						tmp = "0";
					}

					ret = new Short(tmp);
				} else if (sourceType.equals(TYPE_SHORT_OBJ)) {
					ret = obj;
				} else {
					exception = true;
				}
			} else if (targetType.equals(TYPE_LONG_OBJ)) { // convert to Long
				if (sourceType.equals(TYPE_STRING)) {
					String tmp = (String) obj;
					if (tmp == null || tmp.length() < 1) {
						tmp = "0";
					}

					ret = new Long(tmp);
				} else if (sourceType.equals(TYPE_LONG)) {
					String tmp = formatString(obj);
					ret = new Long(tmp);
				} else {
					exception = true;
				}
			} else if (targetType.equals(TYPE_DOUBLE_OBJ)) { // convert to
				// Long
				if (sourceType.equals(TYPE_STRING)) {
					String tmp = (String) obj;
					if (tmp == null || tmp.length() < 1) {
						tmp = "0.0";
					}

					ret = new Double(tmp);
				} else if (sourceType.equals(TYPE_DOUBLE)) {

⌨️ 快捷键说明

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