`
nannan408
  • 浏览: 1783435 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

架构师之bean---------------bean之间的数据copy

 
阅读更多
1.前言.
   如题,bean不能强转,只能对应转换.一共有三种常用方法.
2.代码.
  (1)BeanCopier
public class AccountEntity {
	private int id;
	private Timestamp createTime;
	private BigDecimal balance;
	// Getters and setters are omitted
}
public class AccountDto {
	private int id;
	private String name;
	private String createTime;
	private String balance;
	// Getters and setters are omitted
}
public class BeanCopierConverterTest {

	@Test
	public void noConverterTest() {
		AccountEntity po = new AccountEntity();
		po.setId(1);
		po.setCreateTime(new Timestamp(10043143243L));
		po.setBalance(BigDecimal.valueOf(4000L));
		BeanCopier copier = BeanCopier.create(AccountEntity.class, AccountDto.class, false);
		AccountDto dto = new AccountDto();
		copier.copy(po, dto, null);
		Assert.assertNull(dto.getCreateTime()); // 类型不同,未拷贝
		Assert.assertNull(dto.getBalance()); // 类型不同,未拷贝
	}
}

(2)Converter
package net.sf.cglib.core;

public interface Converter {
    // value 源对象属性,target 目标对象属性类,context 目标对象setter方法名
    Object convert(Object value, Class target, Object context);
}

	@Test
	public void converterTest() {
		AccountEntity po = new AccountEntity();
		po.setId(1);
		po.setCreateTime(Timestamp.valueOf("2014-04-12 16:16:15"));
		po.setBalance(BigDecimal.valueOf(4000L));
		BeanCopier copier = BeanCopier.create(AccountEntity.class, AccountDto.class, true);
		AccountConverter converter = new AccountConverter();
		AccountDto dto = new AccountDto();
		copier.copy(po, dto, converter);
		Assert.assertEquals("2014-04-12 16:16:15", dto.getCreateTime());
		Assert.assertEquals("4000", dto.getBalance());
	}

	static class AccountConverter implements Converter {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		@SuppressWarnings("rawtypes")
		@Override
		public Object convert(Object value, Class target, Object context) {
			if (value instanceof Integer) {
				return (Integer) value;
			} else if (value instanceof Timestamp) {
				Timestamp date = (Timestamp) value;
				return sdf.format(date);
			} else if (value instanceof BigDecimal) {
				BigDecimal bd = (BigDecimal) value;
				return bd.toPlainString();
			}
			return null;
		}
	}


(3)自己写方法fieldName

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

public class Parameter2JavaBean {
	/**
	 * 把req中的数据按照对象的属性取出来并set到对象当中并返回 * 
	 */
	public static <E> E setParameter2JavaBean(HttpServletRequest req, E e) {
		Class<?> clazz = e.getClass();
		Field[] fields = clazz.getDeclaredFields();
		for (Field field : fields) {
			Class<?> typeClass = field.getType();
			String value = req.getParameter(field.getName());
			if (value != null && !"".equals(value)) {
				setValue(e, clazz, field, typeClass, value);
			}
		}
		return e;
	}

	/**
	 * 调用set方法把值set到对象当中 * 
	 * @param obj 指定对象 * @param
	 *  clazz 对象的class * 
	 *  @param field 需要设置值的field对象 *
	 *   @param typeClass field的类型的class *
	 *    @param value 对应的值
	 * @param e
	 * @return
	 */
	private static void setValue(Object obj, Class<?> clazz, Field field,
			Class<?> typeClass, String value) {
		String fieldName = field.getName();
		String methodName = "set" + fieldName.substring(0, 1).toUpperCase()
				+ fieldName.substring(1);
		try {
			Method method = clazz.getDeclaredMethod(methodName,
					new Class[] { typeClass });
			method.invoke(obj,
					new Object[] { getClassTypeValue(typeClass, value) });
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}
	private static Object getClassTypeValue(Class<?> typeClass, String value) {
		if (typeClass == int.class) {
			if (value.equals("")) {
				return 0;
			}
			return Integer.parseInt(value);
		} else if (typeClass == short.class) {
			if (value.equals("")) {
				return 0;
			}
			return Short.parseShort(value);
		} else if (typeClass == byte.class) {
			if (value.equals("")) {
				return 0;
			}
			return Byte.parseByte(value);
		} else if (typeClass == double.class) {
			if (value.equals("")) {
				return 0;
			}
			return Double.parseDouble(value);
		} else if (typeClass == boolean.class) {
			if (value.equals("")) {
				return false;
			}
			return Boolean.parseBoolean(value);
		} else if (typeClass == float.class) {
			if (value.equals("")) {
				return 0;
			}
			return Float.parseFloat(value);
		} else if (typeClass == long.class) {
			if (value.equals("")) {
				return 0;
			}
			return Long.parseLong(value);
		} else {
			return typeClass.cast(value);
		}
	}
}



3.注意.
   推荐用第一种,没有的属性是null.
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics