Reputation: 11
I am using Scannotation to scan classfiles and get all classes with annotations present on any element of that class. Using reflection i've been able to find out all annotations on parameters in methods, but i need objects of those annotations so i can later get its parameters (or what do you call it).
this is fraction of my code, which will return annotations i want, but i can't work with them.
public Set<Class> getParametersAnnotatedBy(Class<? extends Annotation> annotation) {
for (String s : annotated) {
//annotated is set containing names of annotated classes
clazz = Class.forName(s);
for (Method m : clazz.getDeclaredMethods()) {
int i = 0;
Class[] params = m.getParameterTypes();
for (Annotation[] ann : m.getParameterAnnotations()) {
for (Annotation a : ann) {
if (annotation.getClass().isInstance(a.getClass())) {
parameters.add(a.getClass());
//here i add annotation to a set
}
}
}
}
}
}
i know i can work with it, if i know the annotation, like this:
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
public String name();
public int count();
}
// ... some code to get annotations
MyAnnotation ann = (MyAnnotation) someAnnotation;
System.out.println(ann.name());
System.out.println(ann.count());
but so far i was not able to do it this way, using reflection... I would very much appreciate any directions, thanks in advance. PS.: is there any way to get object of parameters like Field for fields, Method for methods etc. ?
Upvotes: 1
Views: 3405
Reputation: 1036
You need to use a.annotationType
. When you call getClass on an annotation you are actually getting its Proxy Class. To get the real class that it is you need to call annotationType
instead of getClass
.
if (annotation.getClass() == a.annotationType()) {
parameters.add(a.annotationType());
// here i add annotation to a set
}
Upvotes: 1