- @interface is used to declare an annotation
format: public @interface AnnotationName{//body} - Each method inside the body declares a config parameter
- function name is parameter name
- return type is parameter type(return type can only be primitive, Class, String, enum)
- can use "default" to declare parameter default value
- if there is only one parameter, normally it's name is "value"
- Normally we use "", or 0 to be default value, we also use -1 to assign the meaning of not exist.
- When using annotation, if there is only one parameter, we don't have to specify parameter name
There are four primitive Annotation
- @Target
- @Retention
- @Documented
- @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