Java将两个JavaBean里相同的字段自动填充

最近因为经常会操作讲两个JavaBean之间相同的字段互相填充,所以就写了个偷懒的方法。记录一下 

/**
	 * 将两个JavaBean里相同的字段自动填充
	 * @param dto 参数对象
	 * @param obj 待填充的对象
	 */
	public static void autoFillEqFields(Object dto, Object obj) {
		try {
			Field[] pfields = dto.getClass().getDeclaredFields();

			Field[] ofields = obj.getClass().getDeclaredFields();

			for (Field of : ofields) {
				if (of.getName().equals("serialVersionUID")) {
					continue;
				}
				for (Field pf : pfields) {
					if (of.getName().equals(pf.getName())) {
						PropertyDescriptor rpd = new PropertyDescriptor(pf.getName(), dto.getClass());
						Method getMethod = rpd.getReadMethod();// 获得读方法

						PropertyDescriptor wpd = new PropertyDescriptor(pf.getName(), obj.getClass());
						Method setMethod = wpd.getWriteMethod();// 获得写方法

						setMethod.invoke(obj, getMethod.invoke(dto));
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 将两个JavaBean里相同的字段自动填充,按指定的字段填充
	 * @param dto
	 * @param obj
	 * @param String[] fields
	 */
	public static void autoFillEqFields(Object dto, Object obj, String[] fields) {
		try {
			Field[] ofields = obj.getClass().getDeclaredFields();

			for (Field of : ofields) {
				if (of.getName().equals("serialVersionUID")) {
					continue;
				}
				for (String field : fields) {
					if (of.getName().equals(field)) {
						PropertyDescriptor rpd = new PropertyDescriptor(field, dto.getClass());
						Method getMethod = rpd.getReadMethod();// 获得读方法

						PropertyDescriptor wpd = new PropertyDescriptor(field, obj.getClass());
						Method setMethod = wpd.getWriteMethod();// 获得写方法

						setMethod.invoke(obj, getMethod.invoke(dto));
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

猜你喜欢

转载自blog.csdn.net/jiayu8706/article/details/85111247