我在类class @ annotation_1和@ annotation_2中有两个注释,这意味着我创建了两个实例。 ---如果有任何错误,请更正此声明!在没有为所有注释方法创建实例的情况下调用带注释的方法
现在,我找到所有使用@ annotation_1或@ annotation_2注解的方法,现在我需要测量每个注释方法所用的时间。
例如,
@annotation_1
Method1
{
...
}
@annotation_2
Method2
{
...
}
@annotation_1
Method3
{
...
}
Method4
{
...
}
现在考虑我需要衡量nanoTime()为每只有@ annotation_1注释每一个方法。所以我用system.nanotime()由
startTime = System.nanoTime();
然后我调用使用
Object obj = null;
try {
startTime = System.nanoTime();
m.invoke(obj);
}finally{
stopTime = System.nanoTime();
runTime = BigDecimal.valueOf(stopTime - startTime);
}
注解的方法,然后使用“m.invoke调用来测量调用之前所采取的方法的时间(OBJ) “,我需要这样做,因为我可能正在访问使用@ annotation_1注释的非静态方法。即我需要调用Method1,然后找到它的runTime,然后调用Method3,然后逐个查找它们的runTime。
但是你可以看到这个调用创建了两个实例,即@ annotation_1和@ annotation_2,尽管我只考虑“annotation_1”注释方法。
我该如何摆脱这种调用。是否有一种替代方法来调用注解了特定注释的方法?
在此先感谢.... :)
编辑:1
要检索方法:
for(Class<?> currentClass: args){
List <Method> methods = Arrays.asList(currentClass.getDeclaredMethods());
for (Method m: methods) {
Annotation[] annotations = m.getDeclaredAnnotations();
for (Annotation annotation: annotations) {
if ((annotation instanceof annotation_1)) {
... //code to find time by invoking method as given above
} else if ((annotation instanceof annotation_2)) {
...//code to find time by invoking method as given above
} else
{
System.err.println("No. definition for annotation : @"+annotation);
}
}
}
}
参数数量采取运行时的所有类名。
发布您用于检索方法的代码。 –
@YazanJaber我编辑了这个问题......请看看...... –
如果您不想创建目标类的多个实例,那么可以缓存该对象的一个实例,并将其用于所有稍后的调用? –