反射常用方法

public Method getMethod(String name, Class<?>... parameterTypes) 

参数: name - 方法名 parameterTypes - 参数Class列表返回:与指定的  name 和  parameterTypes 匹配的  Method 对象

---------------------------------------------------------------------------------------------------------------------------------

public Object invoke(Object obj,Object... args)

参数: obj - 从中调用底层方法的对象 args - 用于方法调用的参数返回:使用参数  args 在  obj 上指派该对象所表示方法的结果


---------------------------------------------------------------------------------------------------------------------------------

/**
	 * 用反射,对比页面和数据库里的自定义字段和选项表
	 * @param newList
	 * @param historyList
	 * @throws Exception
	 * @throws BaseException
	 */
	private void compareItem(List<? extends IBaseDBVO> newList, List<? extends Serializable> historyList, Class<? extends Serializable> voClazz, Class<? extends IBaseDBVO> poClazz,
							 TbQyActivityPO activityPO, Date date) throws Exception, BaseException {
		List<Object> delIdList = new ArrayList<>(); //需删除
		Method poMethod = poClazz.getMethod("getId"); //po的getId方法(newList)
		Method voMethod = voClazz.getMethod("getId"); //vo的getId方法(historyList)
		if(AssertUtil.isEmpty(newList)){ //页面传值为空,直接删除数据库数据
			for(Serializable vo : historyList){
				delIdList.add(voMethod.invoke(vo));
			}
			if(!AssertUtil.isEmpty(delIdList)){
				activityManageDAO.deleteByPks(poClazz, delIdList);
			}
			return;
		}

		//页面传值转成map
		Map<Object, IBaseDBVO> newMap = new HashMap<>();
		for (IBaseDBVO po : newList) {
			newMap.put(poMethod.invoke(po), po);
		}

		IBaseDBVO newPO, clonePO;
		List<IBaseDBVO> removeList = new ArrayList<>(); //从页面传值中需要删除的
		List<IBaseDBVO> updateList = new ArrayList<>(); //需更新
		Object objId;
		for(Serializable historyVO : historyList){
			objId = voMethod.invoke(historyVO); //id
			clonePO = poClazz.newInstance(); //实例new
			BeanHelper.copyFormatProperties(clonePO, historyVO, true);
			if(newMap.containsKey(objId)){ //用于更新
				newPO = newMap.get(objId);
				if (!clonePO.equals(newPO)) {
					updateList.add(newPO);
				}
				removeList.add(newPO);
			}else { //用于删除
				delIdList.add(objId);
				removeList.add(clonePO);
			}
		}
		newList.removeAll(removeList);//需插入

		if(!AssertUtil.isEmpty(delIdList)){
			activityManageDAO.deleteByPks(poClazz, delIdList);
		}
		if(!AssertUtil.isEmpty(updateList)){
			activityManageDAO.execBatchUpdate(updateList);
		}
		if(!AssertUtil.isEmpty(newList)){
			activityManageDAO.execBatchInsert(newList);
		}
	}

猜你喜欢

转载自blog.csdn.net/u012755196/article/details/80899314