一.基本注解
注解就是标注相当于一种标记,就像学生的胸卡,加上了注解就为程序打上了标记。
编译器,开发工具和其他程序来操作类和各种元素的时候可以根据注解做对应的处理。
DK中内置了三个注解分别为:@Override、@Depressed和@SuppressWarnings。
@Override:主要用于子类在覆盖父类方法时,检测方法时候正确,如果是覆盖父类方法,没有提示,否则编译器会报错。
@Depressed:主要使用在:程序在更新升级的时候出现新方法替代了老方法,如果去掉老方法的话调用老方法的类会报错,为了兼容以前的类,同时要提醒新设计的类不建议使用老方法,这时就在老方法上加上@Depressed注解。
@SuppressWarnings:压缩警告,主要用于屏蔽警告,比如已经过时的警告。
@SuppressWarnings的取值如下:
deprecation,使用了过时的类或方法时的警告
unchecked,执行了未检查的转换时的警告
fallthrough,当 Switch 程序块直接通往下一种情况而没有 Break 时的警告
path,在类路径、源文件路径等中有不存在的路径时的警告
serial,当在可序列化的类上缺少serialVersionUID 定义时的警告
finally ,任何 finally 子句不能正常完成时的警告
all,关于以上所有情况的警告
@Target
@Inherited
二.注解反射
Class类中的方法isAnnotationPresent(Class<?
可通过getAnnotation(Class<?
注解定义:
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.MEHTOD,ElementType.TYPE})
public @interface MyAnnotation{
}
注解使用:
eg:
@MyAnnotation
public class AnnotationUse{
public static void main(String[] args){
}
}
注解反射:
eg:
public class AnnotationReflect{
public static void main(String[] args){
boolean isAnno = AnnoationUse.class.isAnnotationPresent(MyAnnotation.class);
if(isAnno){
MyAnnotation an = (MyAnotation)AnnoationUse.class.getAnnotaton(MyAnoation.class);
System.out.println(an);
}
}
}
三.高级注解使用
注解增加属性:
eg:
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE})
public @interface MyAnnotation{
String value();
String color() default "red";
int index() default 15;
}
@MyAnnotation(value="xxx",color="yellow")
public class AnnoationUse{
}
高级注解示例:
eg:定义
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE})
public @interface MyAnnotation{
int[] intArray();
TrafficLamp trafficLamp();
MyOtherAnnotation annotation();
}
使用:
eg:
@MyAnnotation(intArray={11,22,34},trafficLamp=TrafficLamp.RED,annotation=@MyOtherAnnotation("other"))
public class AnnotationUse{
public static void main(String[] args){
}
}
反射:
eg:
import java.util.Arrays;
public class AnnotationReflect{
public static void main(String[] args){
boolean isAt = AnnotationUse.class.isAnnotationPresent(MyAnnation.class);
if(isAt){
MyAnnotation ma = (MyAnnotation)Annotation.class.getAnnotation(MyAnnotation.class);
Arrays.toString(ma.intArray())
ma.trafficLamp();
ma.annotation();
}
}
}