简体   繁体   中英

Java - Parameter annotations

Having trouble getting the parameter annotations of a method, below is a easy to test demonstration, any directions towards the error would be welcome :

// 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);
    }
}

You are not setting implicitly setting the Retention to Runtime, that way it defaults to @Retention (RetentionPolicy.CLASS) this says it is represent in the class file but not present in the VM. To make it work add this to your interface: @Retention (RetentionPolicy.RUNTIME) as class annotatio, then it works again ! :D

While you are at it, you might want to set a specific @Target to only parameters and not methods/fields/classes etc.

By default, annotations are recorded in the class file by the compiler but need not be retained by the VM at run time (RetentionPolicy.CLASS retention policy is being applied).

To change how long annotations are retained, you may use the Retention meta-annotation.

In your case, you want to make it available for reading reflectively so you need it must use RetentionPolicy.RUNTIME to record the annotation in the class file but stil be retained by VM at run time.

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

I also suggest you indicate the program element to which the annotation type At is applicable.

In your case, a parameter annotion should be

 @Target(ElementType.PARAMETER)

this way the compiler will enforce the specified usage restriction.

By default the declared type may be used on any program element:

  • ANNOTATION_TYPE - Annotation type declaration
  • CONSTRUCTOR - Constructor declaration
  • FIELD - Field declaration (includes enum constants)
  • LOCAL_VARIABLE - Local variable declaration
  • METHOD - Method declaration
  • PACKAGE - Package declaration
  • PARAMETER - Parameter declaration
  • TYPE - Class, interface (including annotation type), or enum declaration

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM