java javabean commonly used to convert other objects javabean

Often in the development of the cashback
when the user object when the user object is converted other need to convert each other, the following method may refer to:

/**
	 * 将一个对象转换为另一个对象
	 * @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;
	}

Can also be used after carrying BeanUtils spring has such a function, the introduction of spring-beans and spring-core, there BeanUtils.copyProperties (a, b); another may be achieved between the two copies javabean, to write their own when the study is slightly

Published 10 original articles · won praise 9 · views 450

Guess you like

Origin blog.csdn.net/weixin_43829047/article/details/103388229