Close

Java Reflection - Method.getParameterAnnotations() Examples

Java Reflection Java Java API 


Class:

java.lang.reflect.Method

java.lang.Objectjava.lang.Objectjava.lang.reflect.AccessibleObjectjava.lang.reflect.AccessibleObjectjava.lang.reflect.AnnotatedElementAnnotatedElementjava.lang.reflect.Executablejava.lang.reflect.Executablejava.lang.reflect.MemberMemberjava.lang.reflect.GenericDeclarationGenericDeclarationjava.lang.reflect.Methodjava.lang.reflect.MethodLogicBig

Method:

public Annotation[][] getParameterAnnotations()

Returns an array of arrays of Annotations that represent the annotations on the formal parameters, in declaration order, of the Method represented by this object.


Examples


package com.logicbig.example.method;

import java.lang.annotation.*;
import java.lang.reflect.Method;
import java.util.Arrays;

public class GetParameterAnnotationsExample {

public void displayData(@DisplayConfig Object config) {}

public static void main(String... args) throws NoSuchMethodException {
Method m = GetParameterAnnotationsExample.class.getDeclaredMethod("displayData", Object.class);
Annotation[][] pas = m.getParameterAnnotations();
System.out.println(Arrays.deepToString(pas));
}

@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
private @interface DisplayConfig {}
}

Output

[[@com.logicbig.example.method.GetParameterAnnotationsExample$DisplayConfig()]]




Using multiple annotations:

package com.logicbig.example.method;

import java.lang.annotation.*;
import java.lang.reflect.Method;
import java.util.Arrays;

public class GetParameterAnnotationsExample2 {
public void displayData(@DisplayConfig Object config,
@Deprecated @INDEX int n) {}

public static void main(String... args) throws NoSuchMethodException {
Method m = GetParameterAnnotationsExample2.class.getDeclaredMethod("displayData",
Object.class, int.class);
Annotation[][] pas = m.getParameterAnnotations();
System.out.println("-- all parameter annotations --");
System.out.println(Arrays.deepToString(pas));
for (Annotation[] pa : pas) {
System.out.println("-- parameter annotations --");
for (Annotation annotation : pa) {
System.out.println(annotation);
}
}
}

@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
private @interface INDEX {}

@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
private @interface DisplayConfig {}
}

Output

-- all parameter annotations --
[[@com.logicbig.example.method.GetParameterAnnotationsExample2$DisplayConfig()], [@java.lang.Deprecated(forRemoval=false, since=""), @com.logicbig.example.method.GetParameterAnnotationsExample2$INDEX()]]
-- parameter annotations --
@com.logicbig.example.method.GetParameterAnnotationsExample2$DisplayConfig()
-- parameter annotations --
@java.lang.Deprecated(forRemoval=false, since="")
@com.logicbig.example.method.GetParameterAnnotationsExample2$INDEX()




See Also