views:

103

answers:

2

i am debugging a application using OSGi, i terribly find out that if the Annotation class is missing, the class loader would omit that annotation, if i call the method.getAnnotations(), no exception, but return nothing.

i don't get it, but i do want to know if there is any way to make the JVM throw a Exception. is there any option for starting the JVM?

@Target({ElementType.METHOD}) 
@Retention(RetentionPolicy.RUNTIME) 
@Before 
public @interface Secured { 
   /** Priority **/ public int order() default 0; 
   /** Mapping **/ public String value() default "profile/validate"; 
   /** Required **/ public boolean required() default true; 
   public String role() default "L1"; 
}

Thanks.

+3  A: 

is your annotation retained at runtime? that is it have the @Retetntion annotation set to RUNTIME:

@Retention(RUNTIME)
public @interface YourAnnotation
miaubiz
+2  A: 

Every annotation has a retention defined to it. Retention basically means, in which contexts should the JVM save the annotation. Different values can be seen here. The default behavior is CLASS retention policy, which means the annotations are in the .class files, but aren't used by the JVM. What you want is RUNTIME, whose meaning is clear I guess. Also, there's a SOURCE policy, for annotations that are only relevant during compile-time.

To set the retention policy, you have to annotate the annotation (meta-meta, anyone?), using @Retention, which you can read more about here.

The Java annotation tutorial has a bit more information about this.

abyx