如何用反射获取范型方法
我的大至思路是这样的,但是这样显示
java.lang.NoSuchMethodException: SelectionSort.SelectionSort.sort([Ljava.lang.Integer;
这个错误
Class className=Class.forName(sortName);
Method method=className.getMethod("sort",arr.getClass());141
收起
正在回答
1回答
如果使用课程中的接口,靠字符串来调用相应的类函数,我的实现:
public static <E extends Comparable<E>> void sortTest(String sortname, E[] arr){
try{
Class sortClass = Class.forName(sortname);
Method sortMethod = sortClass.getMethod("sort", Comparable[].class);
Object[] params = new Object[]{arr};
long startTime = System.nanoTime();
sortMethod.invoke(null, params);
long endTime = System.nanoTime();
double time = (endTime - startTime) / 1000000000.0;
if(!SortingHelper.isSorted(arr))
throw new RuntimeException(sortname + " failed");
System.out.println(String.format("%s , n = %d : %f s", sortname, arr.length, time));
}
catch (Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
System.out.println("Error in SortingHelper.sortTest!");
}
}继续加油!:)
相似问题
登录后可查看更多问答,登录/注册
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星