java中常用到的javabean 转换另一javabean 对象

在开发中经常返现对
user对象转换其他的user对象时候需要相互转换时,下面方法可参考:

/**
	 * 将一个对象转换为另一个对象
	 * @param <T1> 要转换的对象
	 * @param <T2> 转换后的类
	 * @param orimodel 要转换的对象
	 * @param castClass 转换后的类
	 * @return 转换后的对象
	 */
	public static  <T1,T2> T2 convertBean(T1 orimodel, Class<T2> castClass) {
		T2 returnModel = null;
		try {
			returnModel = castClass.newInstance();
		} catch (Exception e) {
			throw new RuntimeException("创建"+castClass.getName()+"对象失败");
		}
		/**要转换的字段集合*/
		List<Field> fieldList = new ArrayList<Field>();
		/**循环获取要转换的字段,包括父类的字段*/
		while (castClass != null &&
				!castClass.getName().toLowerCase().equals("java.lang.object")) {
			fieldList.addAll(Arrays.asList(castClass.getDeclaredFields()));
			/**得到父类,然后赋给自己*/
			castClass = (Class<T2>) castClass.getSuperclass();
		}
		for (Field field : fieldList) {
			PropertyDescriptor getpd = null;
			PropertyDescriptor setpd = null;
			try {
				getpd= new PropertyDescriptor(field.getName(), orimodel.getClass());
				setpd=new PropertyDescriptor(field.getName(), returnModel.getClass());
			} catch (Exception e) {
				continue;
			}
			try {
				Method getMethod = getpd.getReadMethod();
				Object transValue = getMethod.invoke(orimodel);
				Method setMethod = setpd.getWriteMethod();
				setMethod.invoke(returnModel, transValue);
			} catch (Exception e) {
				throw  new RuntimeException("cast "+orimodel.getClass().getName()+"to "
						+castClass.getName()+" failed");
			}
		}
		return returnModel;
	}

也可以用spring自带的BeanUtils就有这样的功能,引入spring-beans和spring-core之后,就有BeanUtils.copyProperties(a, b);可以实现两个javabean之间的相互拷贝,自己写的就当是研究咯

发布了10 篇原创文章 · 获赞 9 · 访问量 450

猜你喜欢

转载自blog.csdn.net/weixin_43829047/article/details/103388229