概述
从java1.5以后,jdk提供了注解开发,开发者可以自定义注解。
Annotation并不影响代码的语义,但是它工作的方式被看做类似程序工具或者类库,它反过来对正在运行的程序语义有所影响,annotation可以从源文件、class文件、或者在运行时反射的多种方式被调用。
AnnotatedElement接口
所有的域(类,方法,属性,包等)都实现了这个接口,接口中定义了获得注解的方法
常见的标识性注解
Override:表示是重写的方法
Deprecated:过期的方法,不建议使用的
SuppressWarning消除警告
自定义注解
public @interface MyAnn {
//定义注解的属性,必须要加上()
String value();
}
自定义注解,当注解的属性名是value时,在对其赋值时可以不指定属性的名字,否则必须指定属性名。
需要注意的是这种注解只有在反射调用方法和类的是否才有意义
@Retention
Java.lang.annotation.Retention可以在定义的Annotation中指定编译程序如何对待自定义的Annotation,主要是修饰在注解上。
因为默认是SOURCE,如果要使用自定义注解,一定要设置成RUNTIME
@Retention的使用
@Target
主要标注在注解上,表示被标注的注解可以标注在哪些域上。
public enum ElementType {
TYPE,
FIELD,
METHOD,
PARAMETER,
CONSTRUCTOR,
LOCAL_VARIABLE,
ANNOTATION_TYPE,
PACKAGE
}
@Target的使用
通过反射来获得注解
public static void main(String[] args) throws Exception {
//获得指定类的对象
Class clazz = AnnTest1.class;
//获得指定类的方法
Method method = clazz.getDeclaredMethod("save", new Class[]{});
//判断某个类上是否存在指定的注解
if(method.isAnnotationPresent(Anndemo.class)){
//获得指定的注解
Anndemo annotation = method.getAnnotation(Anndemo.class);
//获得指定注解的内容
String[] values = annotation.value();
for(String val : values){
System.out.println(val);
}
}
//获得指定方法上的所有注解
Annotation[] declaredAnnotations = method.getDeclaredAnnotations();
for(Annotation ann : declaredAnnotations){
System.out.println(ann.toString());
}
}