So, I have created several custom annotations:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Foo {
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Bar {
}
Those annotations are used in my functions:
public class Worker {
@Foo
public void doTaskOne() {...}
@Bar
public void doTaskX() {...}
...
}
I want to use java reflection to check if certain annotation is declared in one method.
for (Method m : methods) {
if (m.isAnnotationPresent(Foo.class)) {
...
} else if (m.isAnnotationPresent(Bar.class)) {
...
}
}
The problem is that since in Java, custom annotation @interface
is not able to be extended. I mean this is illegal:
public @interface Bar extends MyBaseAnnotation{
}
That's I am not able to have a base @interface
for all my custom annotation class Foo
and Bar
. So, if I have a new custom annotation created, I need to add more else if
condition in above method checking code, which sucks! Is there anyway to get rid of this problem? What I want to achieve is to generalize my method checking code to :
for (Method m : methods) {
if (m.isAnnotationPresent(MyBaseAnnotation.class)) {
...
}
}
How to achieve it?
Aucun commentaire:
Enregistrer un commentaire