我需要将代码发送到另一个方法,因为类中的方法数量可能会发生变化,所以我使用反射。但问题是我不能枚举它们在循环中benchmarkMethods.get(i).invoke(set, null);
,因为它有可能给我匿名类只能传递最终变量。我在这种情况下做什么?是否有可能将非最终变量传递给匿名类的方法?
public void RunAllBenchmarks(final Object set, boolean randomOrder) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
final List<Method> benchmarkMethods = new ArrayList<Method >();
final Class benchClass = set.getClass();
Method[] methods = benchClass.getDeclaredMethods();
for (int i = 0; i < methods.length; i++){
Annotation[] annotations = methods[i].getAnnotations();
if (annotations.length != 0){
for (int j = 0; j < annotations.length; j++)
if (annotations[j].annotationType().toString().contentEquals("interface Benchmark"))
benchmarkMethods.add(methods[i]);
}
}
for (int i = 0; i < benchmarkMethods.size(); i++){
String name = null;
Method method = benchmarkMethods.listIterator().next();
MeasureAndRecord(name, new IFunc() {
@Override
public Object onEvent() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
return benchmarkMethods.get(i).invoke(set, null);
}
});
}
PrintWriter writer = new PrintWriter(System.out);
PrintResults(writer);
}
看起来您正在解决您正在处理的实际问题的解决方案。你能否尝试用应用反射描述你试图解决的问题,而不是应用反射的问题? – dasblinkenlight
我正在写一个基准测试,有可能没有反射,但使用它我可以在一个单独的类中添加新的方法。 –
我刚刚开始学习Java,我想知道你是否可以在这里想出一些东西。例如。 Net,它使用委托可以通过,并且一个局部变量 –