I have two annotations in a class say @annotation_1 and @annotation_2 which means that I have created two instances. ---Please correct this statement if there is any error!
Now, I find all the methods that are annotated with @annotation_1 or @annotation_2, now I need to measure time taken by each annotated method.
e.g.,
@annotation_1
Method1
{
...
}
@annotation_2
Method2
{
...
}
@annotation_1
Method3
{
...
}
Method4
{
...
}
Now consider I need to measure nanoTime() for each and every method annotated only with @annotation_1. So I use system.nanotime() to measure the time taken the method before invoking by
startTime = System.nanoTime();
Then I invoke the annotated method using
Object obj = null;
try {
startTime = System.nanoTime();
m.invoke(obj);
}finally{
stopTime = System.nanoTime();
runTime = BigDecimal.valueOf(stopTime - startTime);
}
and then invoking using "m.invoke(obj)", I need to do this because I may be accessing even non-static methods which are annotated with @annotation_1. i.e., I need to invoke Method1 and then find runTime for it, then invoke Method3 and then find runTime for them seperately one after another.
But you could see this invocation creates two instances i.e., for @annotation_1 and @annotation_2, although I consider only "annotation_1" annotated methods.
How do I get rid of this invocation. Is there an alternate method to invoke the methods that are annotated with a specific annotation??
Thanks in advance....:)
Edit : 1
To retrieve the methods:
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);
}
}
}
}
Args take all the class names in run time.