Sunday, January 24, 2016

Declare Annotation

When using @interface to declare an annotation, it inherited  java.lang.annotation.Annotation interface.


  • @interface is used to declare an annotation
    format:   public @interface AnnotationName{//body}
  • Each method inside the body declares a config parameter
  1. function name is parameter name
  2. return type is parameter type(return type can only be primitive, Class, String, enum)
  3. can use "default" to declare parameter default value
  4. if there is only one parameter, normally it's name is "value"
  5. Normally we use "", or 0 to be default value, we also use -1 to assign the meaning of not exist.
  6. When using annotation, if there is only one parameter, we don't have to specify parameter name
There are four primitive Annotation
  1. @Target
  2. @Retention
  3. @Documented
  4. @Inherited
1. @Target
     Specify the annotation apply target, can be package, class, method, variables etc.

2. @Retention
    Specify when it can be applied, either source(.java) file, (.class) file, or in runtime

Declare Annotation Example

//@Target(value=ElementType.METHOD)
@Target(value={ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomAnnotation01 {
 String studentName() default "";
 int age() default 0;
 int id() default -1;
 String[] schools() default {};
}


Using Annotation Example
@CustomAnnotation01(schools = { "" })
public class Demo1 {
 @CustomAnnotation01(studentName="AAA",age=0,id=1001,schools={"aaa","bbb"})
 public void test(){
  
 }
}

To see the basic concept of Annotation: here
To see the full example of how to declare and use annotation: here

No comments:

Post a Comment