注解(Annotation)
@Override:覆盖父类的的方法,如果没有覆盖会报错
@Deprecated:声明某个方法已过时。
@SuppressWarnings:去掉某个方法过时的标志@SuppressWarnings("deprecation")
注解类
@interfaceA{}
应用了“注解类”类
@Aclass B{}
对“应用了注解类的类”进行反射操作的类
classc{
B.class.isAnnotionPresent(a.class);
Aa = B.class.getAnnotion(A.class);
};
注解出现的位置
元注解
@Retention(RetentionPolicy.RUNTIME);使注解出现在内存中;@Deprecated
@Retention(RetentionPolicy.SOURCE);使注解出现在源码中,@SuppressWanrning(),@Override
@Retention(RetentionPolicy.CLASS);是注解出现在class文件中
自定义注解
@Retention(RetentionPolicy.RUNTIME)
public@interface ItcastAnnotation {
}
@ItcastAnnotation
publicclass AnnotationTest {
/**
* @param args
*/
publicstatic void main(String[] args) {
//TODO Auto-generated method stub
判断AnnotationTest类在内存中的字节码对象中是否有ItcastAnnotation.class注解(RUNTIME)
if(AnnotationTest.class.isAnnotationPresent(ItcastAnnotation.class)){
ItcastAnnotationitcast = AnnotationTest.class.getAnnotation(ItcastAnnotation.class);
System.out.println(itcast);
}
}
}
元注解
@Target({ElementType.METHOD,ElementType.Type})
用来说明某个注解必须使用在哪种类型上,例如方法,类了
@Target(ElementType.METHOD)
public@Interface A{} 则A注解必须用在方法上
为注解添加属性
@Retention(RetentionPolicy.RUNTIME)
public@interface ItcastAnnotation {
Stringcolor() default "blue";//为属性设置默认值
Stringvalue();//当只有value时,可以省略"value ="例如@ItcastAnnotation("red")
int[]arrayAttr();//数组当为属性@ItcastAnnotation(value = "red",arrayAttr = {1,2})
如果只有一个值,可以省略{}
EnumTest.Trafficlamplamp() default EnumTest.Trafficlamp.RED;//枚举属性
MetaAnnotationvalue() default@MetaAnnotation("lhm");//属性为一个注解使用@ItcastAnnotation(value= "red",
arrayAttr= {1,2},value = @MetaAnnotation("add"));//打印itcast.value().value();
}
@ItcastAnnotation(color = "red")//以属性的方式设置值
publicclass AnnotationTest {
/**
* @param args
*/
publicstatic void main(String[] args) {
//TODO Auto-generated method stub
if(AnnotationTest.class.isAnnotationPresent(ItcastAnnotation.class)){
ItcastAnnotationitcast = AnnotationTest.class.getAnnotation(ItcastAnnotation.class);
System.out.println(itcast.color());//以方法的形式取出属性值
}
}
}