注解(Annotation):
JDK5.0引进,不是必需品,是优化品。
作用:
1:不是程序本身,可以对程序作出解释(检查,约束)。
2:可以被其他程序(比如编译器)读取。
格式:
1:以“@注释名”在代码种存在,还可以添加一些参数值。
如:
@SuppressWarnings(value="unchecked")
位置:
可以在package,class,method,field等上门,相当于添加了额外的辅助信息,我们可以通过反射机制编程实现对这些元数据的访问。
内置注解:
@Override //重写
@Deprecated //表示不鼓励程序员使用,通常是因为它很危险或者有更好的选择
@SuppressWarnings //抑制编译时的警告信息
元注解:
负责解释其他注解。
@Target(value=ElementType.METHOD) //用于描述注解的使用范围
@Retention //表示需要在什么级别保存该注释信息(在什么时候有效),用于描述注解的生命周期(SOURCE<CLASS<RUNTIME)
@Document //说明该注解将被包含在javadoc里面
@Inherited //说明子类可以继承父类中的该注解
自定义注解:
使用@interface自定义注解
格式:public @interface 注释名{自定义内容}
注解元素必须要有值
//自定义注解
public class Test{
@MyAnnotation(name="song")
public void test(){
}
@MYAnnotation("song")
public void test1(){
}
}
@Target({ELementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation{
//注解的参数:参数类型+参数名();
String name(); //默认值:default ""
int age() default 0;
int id() default -1;//如果默认值为-1,代表不存在
String[] schools() default{""};
}
//如果注解只有一个值,使用value命名,那么调用时就不用写成value=""而是直接""
@Target({ELementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface Myannotation1{
String value();
}