自定义BeanUtil 实现dto之间转换

public class BeanUtil{
	public static <T> T transfrom(Class<T> clazz, Object src) {
		if (src == null) {
			return null;
		}
		T instance = null;
		try {
			instance = clazz.newInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
		org.springframework.beans.BeanUtils.copyProperties(src, instance, getNullPropertyNames(src));
		return instance;
	}
	private static String[] getNullPropertyNames(Object source) {
	    // 忽略null 赋值
		final BeanWrapper src = new BeanWrapperImpl(source);
		PropertyDescriptor[] pds = src.getPropertyDescriptors();

		Set<String> emptyNames = new HashSet<String>();
		for (PropertyDescriptor pd : pds) {
			Object srcValue = src.getPropertyValue(pd.getName());
			if (srcValue == null) emptyNames.add(pd.getName());
		}
		String[] result = new String[emptyNames.size()];
		return emptyNames.toArray(result);
	}

	public static void main(String[] args) {
		User user = new User();
		user.setPerson(new Person());
		user.setBaseId(1);
		UserDto transfrom = BeanUtil.transfrom(UserDto.class, user);
		System.out.println(transfrom.toString());
	}
}

 

posted @ 2019-07-18 14:29  缘来是妳啊  阅读(130)  评论(0编辑  收藏  举报