我在類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我編輯了這個問題......請看看...... –
如果您不想創建目標類的多個實例,那麼可以緩存該對象的一個實例,並將其用於所有稍後的調用? –