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

时间:2021-09-14 10:58:20

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


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

public class RequestUploadXmlData<T> {

private Root<T> root;

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

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

}

public class Root<T> {	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 <T> String upload(String jkid, String WriteXmlDoc, Class<T> obj, Object objDao) throws Exception {		JSONObject xmlJSONObj = XML.toJSONObject(WriteXmlDoc);		RequestUploadXmlData<T> requestUploadXmlData = JsonUtil.fromRequest(xmlJSONObj.toString(),				new TypeToken<RequestUploadXmlData<T>>() {				}.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<? extends Object> 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 <T> String upload(String jkid, String WriteXmlDoc, Class<T> obj, Object objDao) throws Exception {

JSONObject xmlJSONObj = XML.toJSONObject(WriteXmlDoc);
RequestUploadXmlData<T> requestUploadXmlData = JsonUtil.fromRequest(xmlJSONObj.toString(),
new TypeToken<RequestUploadXmlData<T>>() {
}.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<? extends Object> objClass = objDao.getClass();
Method declaredMethod = objClass.getMethod("insert", obj);
/** 使用json进行类型转换,避免getVehispara返回map<String>导致异常: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<String>类型,导致类型不匹配,至于为什么是这种类型,抱歉,目前没时间研究,我也不知道。