Inspecting annotations of the method's parameters

Having a method, we can inspect the annotations of its parameters by calling getParameterAnnotations():

This method returns a matrix (array of arrays) containing the annotations on the formal parameters, in declaration order:

Class<Melon> clazz = Melon.class;
Method methodSlice = clazz.getDeclaredMethod("slice", int.class);
Annotation[][] paramAnnotations
= methodSlice.getParameterAnnotations();

Fetching each parameter type with its annotations (in this case, we have an int parameter with two annotations) can be accomplished via getParameterTypes(). Since this method maintains the declaration order as well, we can extract some information, as follows:

Class<?>[] parameterTypes = methodSlice.getParameterTypes();

int i = 0;
for (Annotation[] annotations: paramAnnotations) {
Class parameterType = parameterTypes[i++];
System.out.println("Parameter: " + parameterType.getName());

for (Annotation annotation: annotations) {
System.out.println("Annotation: " + annotation);
System.out.println("Annotation name: "
+ annotation.annotationType().getSimpleName());
}
}

And, the output should be as follows:

Parameter type: int
Annotation: @modern.challenge.Ripe(value=true)
Annotation name: Ripe
Annotation: @modern.challenge.Shape(value="square")
Annotation name: Shape
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.54.255