Reputation: 1361
This is my scenario "I have a abstract class. There are many derived classed extending this abstract class with the use of annotations. In addition, I have a method of abstract class, that was reflected all notations in one particular derived class".
// Here's a definition of annotation
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface SampleAnnotation {
int sample();
}
public abstract class A {
// Here's a method to reflect all annotations
// in particular derived class like B or C
@Override
public void foo() {
}}
public class B extends A {
@SampleAnnotation (sample = 1)
public void step1() {}
@SampleAnnotation (sample = 2)
public void step2() {}
}
public class C extends A {
@SampleAnnotation (sample = 1)
public void step1() {}
@Sample (stage = 2)
public void step2() {}
}
How can I use java reflection to reflect all the annotations in specific derived class like B or C ?
Upvotes: 3
Views: 1325
Reputation: 29493
It depends:
The first one can be achieved with a method implementation of foo
like this:
public void foo() {
for (Method method : this.getClass().getDeclaredMethods()) {
for (Annotation a : method.getAnnotations()) {
// do something with a
}
}
}
Then you can invoke foo
from your concrete class, for instance:
new B().foo();
For the second case you will need to do class path scanning as Peter Lawrey has pointed out.
Upvotes: 1
Reputation: 533492
Perhaps what you have in mind is this Reflections library.
Using Reflections you can query your metadata such as:
- get all subtypes of some type
- get all types/methods/fields annotated with some annotation, w/o annotation parameters matching
- get all resources matching matching a regular expression
Upvotes: 3