自个在写自动化测验工具有关thrift效劳自动化测验遇到的疑问
首先给大家看一段代码
Java代码 保藏代码
public static void test(Listlist){
System.out.println(list.get(0));
System.out.println(list.get(0) + 123);
System.out.println(list.get(0).getClass());
}
public static void bugTest1(){
澳洲保健品http://www.eget.com.au
国医一号http://www.tdhzp.com
号码大全http://www.haomad.com
临沂购http://www.shoudashou.com
String json = "[50004172,926513792]";
for(Method m :ThriftGenUtils.class.getMethods()){
if("test".equals(m.getName())){
for(Class pClass : m.getParameterTypes()){
Object argCasted = Json.strToObj(json, pClass);
try {
m.invoke(new ThriftGenUtils(),argCasted);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
}
运转bugTest1
疑问:
1 argCasted详细类型为List,其间的泛型详细类型为何类型?为何?
2 invoke是不是能成功?
3 若invoke成功了,list的泛型详细类型是啥类型?test是不是能够成功运转?若不能成功运转,到哪一行犯错?报啥过错?为何?
答案:
1 Integer,m.getParameterTypes()获取到的泛型类型是不包括详细类型的,也即是Json.strToOb调用的时分pClass仅仅传了List,Json变换的时分只知道是数据类型,默许转成Integer,浮点数转为Double。
2 是
3 Integer,不能成功,到219行报类型变换反常Integer不能变换为Long类型,原因是泛型类型擦除。(泛型类型擦除:http://blog.csdn.net/caihaijiang/article/details/6403349 )
当前的解决方案为获取到泛型类型及详细类型,经过ObjectMapper.getTypeFactory().constructParametricType(clazz,genericClazzes)来获取javaType再来变换成Object目标
改造后,完成的有关代码如下
Java代码 保藏代码
Method method = null;
ListargList = new ArrayList<>();
for (Method m : clientClazz.getMethods()){
if(!methodName.equals(m.getName())){continue;}
method = m;
Type[] types = m.getGenericParameterTypes();
Class[] classes = m.getParameterTypes();
int i = 0;
for ( Type c: types) {
int index = i++;
String arg = args[index];
if(!(c instanceof ParameterizedType)){
String jsonStr = Json.ObjToStr(arg);
argList.add(Json.strToObj(jsonStr,classes[index]));
continue;
}
ParameterizedType pt = (ParameterizedType) c;
ObjectMapper mapper = new ObjectMapper();
Class[] genericClazzes = new Class[pt.getActualTypeArguments().length];
int j = 0;
for(Type type : pt.getActualTypeArguments()){
genericClazzes[j ++] = (Class) type;
}
JavaType javaType = mapper.getTypeFactory().constructParametricType(classes[index],genericClazzes);
Object argCasted = mapper.readValue(arg,javaType);
argList.add(argCasted);
}
break;
}
if ( method != null){
res = method.invoke(obj,argList.toArray());
}
转载于:https://blog.51cto.com/8917152/1544255