元注解:
@Target:表明被注解注解的作用域(类、方法、属性等等)
@Retention:表明被注解注解的作用时间。只有三个(只在源文件、编译时保留、运行时保留)。一般自定义的注解都设置为运行时保留
@Document:表明被注解的注解会保留在doc文档中
@Inherited:表明被注解的注解所在类的子类可以继承该注解
注解的变量:
注解的变量声明方法是:返回值类型 变量名();(可以设置默认值)
自定义注解:
自定义注解的声明:
@interface 注解名{
}
注解事项:
如果注解有参数,那么除非参数名为value,否则在填写参数的时候必须带上参数名。如age =…;
class DeprecatedTest{
@Deprecated//表明方法已经过时但是仍可以使用
public void a(){
System.out.println("不建议使用");
}
}
class OverrideTest{
@Override//表明要重写父类方法,如果写的方法父类没有的话会报错
public String toString(){
super.toString();
return "重写注解";
}
}
class SuppressWarningsTest{
@SuppressWarnings("all")//抑制警告
public void test(){
List list =new ArrayList();
}
}
@myannotation(name ="da",age =10,schools = "adad")//自定义的注解
class AnnotationTest2{
@myannotation2("ada")
public void Test(){
}
}
//自定义注解
@Target({ElementType.METHOD,ElementType.TYPE})//元注解。定义myannotation注解的作用域
@Retention(RetentionPolicy.RUNTIME)//元注解。定义myannotation注解的作用时间
@Documented//元注解。表明myannotation注解会被包含在doc文档中
@Inherited//元注解。表明子类可以继承myannotation注解
@interface myannotation{
String name() default "";
int age()default -1;//如果默认值为-1表示不存在,找不到值。类似于indexof方法,找不到也是返回-1
String [] schools() default {"adad","adad"};
}
//自定义的注解
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface myannotation2{
String value();//只有名字是value才能在使用的时候默认不写名字。换成其他名字不可以
}