注解经常与反射搞在一起,本文以一个例子全面勾勒出一个复杂的注解,方便理解。
package Plan2.annotation;
//JDK1.5引入注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
public class Test01 {
//注解可以显式赋值,如果没有默认值,必须要赋值
@MyAnnotation(age=22)
public void test(){
}
@MyAnnotation2("张老师")
public void test2(){
}
}
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation{
//注解的参数--参数类型+参数名+() 可以再加上默认值
String name() default "666";
int age();
int id() default -1;
String[] schools() default {"清华","北大"};
}
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2 {
//不成文的规定: 如果只有一个参数,且参数名为value,那么用注解时 可以不用写参数名 value=
String value();
}