java反射泛型异常:argument type mismatch解决方案

最近使用java反射泛型的时候出现异常:argument type mismatch,经过debug排查终于解决,废话不说,直接上代码:


javabean及相应的执行函数如下所示:

public class RequestUploadXmlData {

	private Root root;

	/**
	 * @return the root
	 */
	public Root getRoot() {
		return root;
	}

	/**
	 * @param root
	 *            the root to set
	 */
	public void setRoot(Root root) {
		this.root = root;
	}

}

public class Root {

	private T vehispara;
	
	/**
	 * @return the vehispara
	 */
	public T getVehispara() {
		return vehispara;
	}

	/**
	 * @param vehispara the vehispara to set
	 */
	public void setVehispara(T vehispara) {
		this.vehispara = vehispara;
	}
	
	
}

public  String upload(String jkid, String WriteXmlDoc, Class obj, Object objDao) throws Exception {

		JSONObject xmlJSONObj = XML.toJSONObject(WriteXmlDoc);
		RequestUploadXmlData requestUploadXmlData = JsonUtil.fromRequest(xmlJSONObj.toString(),
				new TypeToken>() {
				}.getType(), "yyyy-MM-dd HH:mm:ss"); 

		String webResult = WebServiceUtil.upload("", jkid, WriteXmlDoc);
		xmlJSONObj = XML.toJSONObject(webResult);
		UploadResult uploadResult = JsonUtil.fromRequest(xmlJSONObj.toString(), UploadResult.class);

		/** 如果上传成功则插入数据 */
		if (CustomData.CODE_SUCCESS.equals(uploadResult.getRoot().getHead().getCode())) {
			
			Class objClass = objDao.getClass();
			Method declaredMethod = objClass.getMethod("insert", obj);			
			T vehispara = requestUploadXmlData.getRoot().getVehispara();
			declaredMethod.invoke(objDao, vehispara);
			/*tdlxxDao.insert(requestUploadXmlData.getRoot().getVehispara());*/
			
		}

		return webResult;
	}

执行后报异常:java.lang.IllegalArgumentException: argument type mismatch

解决方案

public  String upload(String jkid, String WriteXmlDoc, Class obj, Object objDao) throws Exception {

		JSONObject xmlJSONObj = XML.toJSONObject(WriteXmlDoc);
		RequestUploadXmlData requestUploadXmlData = JsonUtil.fromRequest(xmlJSONObj.toString(),
				new TypeToken>() {
				}.getType(), "yyyy-MM-dd HH:mm:ss"); 

		String webResult = WebServiceUtil.upload("", jkid, WriteXmlDoc);
		xmlJSONObj = XML.toJSONObject(webResult);
		UploadResult uploadResult = JsonUtil.fromRequest(xmlJSONObj.toString(), UploadResult.class);

		/** 如果上传成功则插入数据 */
		if (CustomData.CODE_SUCCESS.equals(uploadResult.getRoot().getHead().getCode())) {
			
			Class objClass = objDao.getClass();
			Method declaredMethod = objClass.getMethod("insert", obj);
			/** 使用json进行类型转换,避免getVehispara返回map导致异常:argument type mismatch */
			String json = JsonUtil.toJson(requestUploadXmlData.getRoot().getVehispara());
			T vehispara = JsonUtil.fromRequest(json, obj);
			declaredMethod.invoke(objDao, vehispara);
			/*tdlxxDao.insert(requestUploadXmlData.getRoot().getVehispara());*/
			
		}

		return webResult;
	}

原因是requestUploadXmlData.getRoot().getVehispara()返回的是map类型,导致类型不匹配,至于为什么是这种类型,抱歉,目前没时间研究,我也不知道。

你可能感兴趣的:(java)