java Vo和Model的转换工具

声明:是将项目中的内容总结出来的。

Model类的属性和数据表中的字段是一一对应的,Vo首先属性值也是要和Model类中的属性一一对应,其次Vo也可以有自己的额外属性。

下面先将工具贴出:

package test;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @CLASS:BeanUtils
 * @DESCRIPTION:vo和model相互转换(说白了就是相互赋值的问题)
 * @AUTHOR:yehui
 * @VERSION:v1.0
 * @DATE:2013-4-15 下午2:56:02
**/
public class BeanUtils {
	private static final Set<Class<?>>	SIMPLE_TYPE_SET	= new HashSet<Class<?>>();

	static {
		SIMPLE_TYPE_SET.add(Character.class);
		SIMPLE_TYPE_SET.add(String.class);
		SIMPLE_TYPE_SET.add(Integer.class);
		SIMPLE_TYPE_SET.add(Long.class);
		SIMPLE_TYPE_SET.add(Float.class);
		SIMPLE_TYPE_SET.add(Double.class);
		SIMPLE_TYPE_SET.add(Boolean.class);
		SIMPLE_TYPE_SET.add(java.util.Date.class);
		SIMPLE_TYPE_SET.add(java.sql.Date.class);
		SIMPLE_TYPE_SET.add(java.sql.Timestamp.class);
		SIMPLE_TYPE_SET.add(BigDecimal.class);
	}

	/**
	 * model转换为vo
	 * 
	 * @param vo
	 *            vo的class
	 * @param model
	 *              model对象
	 * @return vo对象
	 */
	public static <T extends Object> T copyModelToVo(Class<T> vo,
			BaseModel model) {
		T v = null;
		try {
			v = vo.newInstance();
			copy(model, v);
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return v;
	}

	/**
	 * model转换为vo的list
	 * 
	 * @param vo
	 *           vodeclass
	 * @param models
	 *            model的list
	 * @return vo的list
	 */
	public static <T extends Object> List<T> copyModelToVo(Class<T> vo,
			List<? extends BaseModel> models) {
		List<T> list = new ArrayList<T>();
		if (models != null) {
			for (BaseModel model : models) {
				list.add(copyModelToVo(vo, model));
			}
		}
		return list;
	}

	/**
	 * vo转换为model
	 * 
	 * @param model
	 *            model的class
	 * @param vo
	 *            vode对象
	 * @return model的对象
	 */
	public static <T extends BaseModel> T copyVoToModel(Class<T> model,
			Object vo) {
		T m = null;
		try {
			m = model.newInstance();
			copy(model, m);
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return m;
	}

	/**
	 * vo转换为model list
	 * 
	 * @param model
	 *            model的class
	 * @param vos
	 *            vo的list
	 * @return model的list
	 */
	public static <T extends BaseModel> List<T> copyVoToModel(Class<T> model,
			List<? extends Object> vos) {
		List<T> list = new ArrayList<T>();
		if (vos != null) {
			for (Object vo : vos) {
				list.add(copyVoToModel(model, vo));
			}
		}
		return list;
	}

	private static Object copy(Object source, Object target) {
		if (target == null || source == null)
			return null;
		// 获得源文件的class
		Class<?> sourceClass = source.getClass();
		// 获得要转换后的目标文件的class
		Class<?> targetClass = target.getClass();
		// 获得源文件的的fields
		Field[] sourceFields = sourceClass.getDeclaredFields();

		for (int i = 0; i < sourceFields.length; i++) {
			try {
				// 获得目标文件的Field
				Field temp = targetClass.getDeclaredField(sourceFields[i]
						.getName());
				// 根据field获得属性名称
				String fieldName = temp.getName();
				// 获得属性的类型
				Class<?> fieldType = temp.getType();
				// 获得属性的get,set方法
				String getMethodName = "get"
						+ fieldName.substring(0, 1).toUpperCase()
						+ fieldName.substring(1);
				String setMethodName = "set"
						+ fieldName.substring(0, 1).toUpperCase()
						+ fieldName.substring(1);
				Method getMethod = sourceClass.getMethod(getMethodName);
				Method setMethod = targetClass.getMethod(setMethodName,
						new Class[] { fieldType });
				Object value = getMethod.invoke(source);
				// 判断value的类型
				if (value != null) {
					if (SIMPLE_TYPE_SET.contains(value.getClass())) {
						if (value instanceof String) {
							String s = (String) value;
							value = s != null ? s.trim() : null;
						}
						if (value instanceof String
								&& !fieldType.equals(String.class)) {
							value = stringToObj(fieldType, (String) value);
						}
						if (!(value instanceof String)
								&& fieldType.equals(String.class)) {
							value = objToString(value);
						}
						setMethod.invoke(target, new Object[] { value });
					} else if (value instanceof Collection) {
					} else {
						Object obj = copy(value, fieldType.newInstance());
						setMethod.invoke(target, new Object[] { obj });
					}
				} else {
					setMethod.invoke(target, new Object[] { null });
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return target;
	}

	private static Object stringToObj(Class<?> clazz, String value) {
		Object obj = null;
		if (value == null)
			return null;
		if (clazz.equals(Integer.class)) {
			obj = Integer.valueOf(value);
		} else if (clazz.equals(Long.class)) {
			obj = Long.valueOf(value);
		} else if (clazz.equals(Float.class)) {
			obj = Float.valueOf(value);
		} else if (clazz.equals(Double.class)) {
			obj = Double.valueOf(value);
		} else if (clazz.equals(Boolean.class)) {
			obj = Boolean.valueOf(value);
		} else if (clazz.equals(BigDecimal.class)) {
			obj = new BigDecimal(value);
		} else if (clazz.equals(java.util.Date.class)) {
			try {
				if (value.length() == 19) {
					java.text.DateFormat df = new java.text.SimpleDateFormat(
							"yyyy-MM-dd HH:mm:ss");
					obj = df.parse(value);
				} else if (value.length() == 16) {
					java.text.DateFormat df = new java.text.SimpleDateFormat(
							"yyyy-MM-dd HH:mm");
					obj = df.parse(value);
				} else {
					java.text.DateFormat df = new java.text.SimpleDateFormat(
							"yyyy-MM-dd");
					obj = df.parse(value);
				}
			} catch (Exception e) {
			}
		} else if (clazz.equals(Character.class)) {
			obj = value.charAt(0);
		}

		return obj;
	}

	private static String objToString(Object obj) {
		String value = null;
		if (obj == null)
			return null;
		if (obj instanceof java.util.Date) {
			java.text.DateFormat df = new java.text.SimpleDateFormat(
					"yyyy-MM-dd");
			value = df.format((java.util.Date) obj);
		} else {
			value = obj.toString();
		}
		return value;
	}

	public static void main(String[] args) {

		VoUsers resUser = new VoUsers();
		ResUser user = new ResUser();
		user.setUSER_ID("12");
		user.setUSER_NAME("hh");
		user.setUSER_PASSWORD("123");
		// 将model转换为vo
		resUser = BeanUtils.copyModelToVo(resUser.getClass(), user);
		// 输出vo的值
		System.err.println(resUser.toString());
	}
}

Model的基础类,model类必须继承这个类和Vo也可以继承这个类

/**
 * @FILE:BaseModel.java
 * @AUTHOR:hui-ye
 * @DATE:2013-5-14 下午4:43:30
 **/
package test;

import java.io.Serializable;
import java.lang.reflect.Field;

/**
 * @CLASS:BaseModel
 * @DESCRIPTION:model的基础类
 * @AUTHOR:yehui
 * @VERSION:v1.0
 * @DATE:2013-4-15 8:46:11
**/

public class BaseModel implements Serializable {
	public static final String	FUNCTION_COMPILE	= "compile";

	@Override
	public String toString() {
		Field[] field = this.getClass().getDeclaredFields();
		String s = "";
		try {
			for (Field f : field) {
				f.setAccessible(true);
				s += ","
						+ f.getName()
						+ "="
						+ (f.get(this) == null ? "null" : f.get(this)
								.toString());
			}
			// if (!StringUtils.isEmpty(s)) {
			// s = s.substring(1);
			// }
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return s;
	}

}

Model类

/**
 * @FILE:片段.java
 * @AUTHOR:hui-ye
 * @DATE:2013-5-14 下午4:45:19
 **/
package test;

import java.io.Serializable;

/*******************************************
 * 
 * @CLASS:ResUser
 * @DESCRIPTION:	
 * @AUTHOR:hui-ye
 * @VERSION:v1.0
 * @DATE:2013-5-14 下午4:45:19
 *******************************************/
public class ResUser  extends BaseModel{

	private String USER_ID; //id
	private String USER_NAME; //name
	private String USER_PASSWORD; //password

	public String getUSER_ID() {
		return USER_ID;
	}
	public void setUSER_ID(String uSER_ID) {
		USER_ID = uSER_ID;
	}
	public String getUSER_NAME() {
		return USER_NAME;
	}
	public void setUSER_NAME(String uSER_NAME) {
		USER_NAME = uSER_NAME;
	}
	public String getUSER_PASSWORD() {
		return USER_PASSWORD;
	}
	public void setUSER_PASSWORD(String uSER_PASSWORD) {
		USER_PASSWORD = uSER_PASSWORD;
	}

}

Vo类

/**
 * @FILE:VoUsers.java
 * @AUTHOR:hui-ye
 * @DATE:2013-5-14 下午4:49:16
 **/
package test;

import java.io.Serializable;

/*******************************************
 * 
 * @CLASS:VoUsers
 * @DESCRIPTION:	
 * @AUTHOR:hui-ye
 * @VERSION:v1.0
 * @DATE:2013-5-14 下午4:49:16
 *******************************************/
public class VoUsers extends BaseModel{

	private String USER_ID; //id
	private String USER_NAME; //name
	private String USER_PASSWORD; //password

	public String getUSER_ID() {
		return USER_ID;
	}
	public void setUSER_ID(String uSER_ID) {
		USER_ID = uSER_ID;
	}
	public String getUSER_NAME() {
		return USER_NAME;
	}
	public void setUSER_NAME(String uSER_NAME) {
		USER_NAME = uSER_NAME;
	}
	public String getUSER_PASSWORD() {
		return USER_PASSWORD;
	}
	public void setUSER_PASSWORD(String uSER_PASSWORD) {
		USER_PASSWORD = uSER_PASSWORD;
	}
	
}


好了,基本就这些了,可以明确的支出这个工具就是为了两个类的对象相互赋值,没有其他的意思。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值