![](/img/trans.png)
[英]Java 8, Google Reflections -- Get Annotated Types as List of Annotations, not Class<?>
[英]help with reflections and annotations in java
除了我自己缺乏更有效地執行代碼的能力外,我無緣無故地將代碼加倍...
for (Method curr: all){
if (curr.isAnnotationPresent(anno)){
if (anno == Pre.class){
for (String str : curr.getAnnotation(Pre.class).value()){
if (str.equals(method.getName()) && curr.getReturnType() == boolean.class && curr.getParameterTypes().length == 0){
toRun.add(curr);
}
}
} if (anno == Post.class) {
for (String str : curr.getAnnotation(Post.class).value()){
if (str.equals(method.getName()) && curr.getReturnType() == boolean.class && curr.getParameterTypes().length == 0){
toRun.add(curr);
}
}
}
}
}
anno是一個參數-Class Class<? extends Annotation>
Class<? extends Annotation>
, Pre
和Post
是我的注釋,它們都有一個value()
,它是一個字符串數組。
當然,這全都歸因於我讓Eclipse自動填充我尚不了解的代碼這一事實。
如果說“更有效”是指“用更少的代碼行”,那么為什么不合並兩個if語句呢? 我可以看到的唯一區別是,一個具有Pre.class
,另一個具有Post.class
,並且您已經在anno var中方便地使用了該類引用:
for (Method curr : all) {
if (curr.isAnnotationPresent(anno)) {
if (anno == Pre.class || anno == Post.class){
for (String str : curr.getAnnotation(anno).value()){
if (str.equals(method.getName()) && curr.getReturnType() == boolean.class && curr.getParameterTypes().length == 0){
toRun.add(curr);
}
}
}
}
}
除此之外,如果anno
既不是Pre.class
也不是Post.class
,那么進行外部for循環是沒有Pre.class
,因此您應該在外部進行檢查(如果使用不需要的注釋調用它,可以節省遍歷方法的時間) )。 您還可以將對returnType和參數長度的檢查移到內部for循環之外(這樣可以節省對每個值重復的檢查,如果不正確,則可以完全保存迭代)。
if (anno == Pre.class || anno == Post.class){
for (Method curr : all) {
if (curr.isAnnotationPresent(anno) && curr.getReturnType() == boolean.class && curr.getParameterTypes().length == 0) {
for (String str : curr.getAnnotation(anno).value()){
if (str.equals(method.getName())) {
toRun.add(curr);
}
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.