Java - parameter annotations

With no way to get method parameter annotations, below is a simple demo, any directions to error would be welcomed:

// Annotation
public @interface At {}

// Class
public class AnnoTest {

   public void myTest(@At String myVar1, String myVar2){}
}

// Test
public class App {

    public static void main(String[] args) {

        Class myClass = AnnoTest.class;

        Method method = myClass.getMethods()[0];
        Annotation[][] parameterAnnotations = method.getParameterAnnotations();

        // Should output 1 instead of 0
        System.out.println(parameterAnnotations[0].length);
    }
}

      

+3


source to share


2 answers


You are not implicitly setting the installation Retention

to Runtime, so it defaults to @Retention (RetentionPolicy.CLASS)

, which says it represents in the class file but is not present in the VM. To make it work add this to your interface: @Retention (RetentionPolicy.RUNTIME)

like annotatio class, then it works again!: D



While you're at it, you may only need to set @Target

parameters, not methods / fields / classes, etc.

+3


source


By default, annotations are written to the class file by the compiler, but must not be persisted by the VM at runtime (the RetentionPolicy.CLASS retention policy applies).

To change the duration of annotations, you can use the hold meta annotation.

In your case, you want to make it readable reflexively so that it needs it, it should use RetentionPolicy.RUNTIME to write the annotation in the class file, but keep it at VM runtime.

@Retention(RetentionPolicy.RUNTIME)
public @interface At {}

      


I also suggest that you specify the program element to which the At annotation type applies.



In your case, the parameter annotation should be

 @Target(ElementType.PARAMETER)

      

thus, the compiler will fulfill the specified restriction of use.

By default, a declared type can be used for any program item:

  • ANNOTATION_TYPE - annotation type declaration
  • CONSTRUCTOR - constructor declaration
  • FIELD - field declaration (includes enumeration constants)
  • LOCAL_VARIABLE - local variable declaration
  • METHOD - Method declaration
  • PACKAGE - Package declaration
  • PARAMETER - Parameter declaration
  • TYPE - class, interface (including annotation type) or enumeration declaration
+1


source







All Articles