Java注解
1.概念
1.1 Annotation其实是代码里的特殊标记,这些标记可以在编译,类加载,运行时被读取,并执行相应的处理。
2. java在java.lang下提供了5个基本Annotation
2.1 @Override,@Deprecated ,@Suppress Warnings,@FunctionlInterfac,@SafeVarags
- @Override: 用来指定方法重写,它可以强制一个子类必须覆盖父类的方法,@Override的作用是告诉编译器检查这个方法,保证父类要包含被该方法重写的方法,否则就会编译出错,@Override:”覆盖” 主要是帮助程序员避免一些低级错误。
- @Deprecated:”弃用” 用于表示某个程序元素(类,方法等)已过时,当其他程序使用已过时的类,方法时,编译器会给出警告。
- @Suppress Warnings:”抑制 警告” 用于取消显示指定的编译器警告
- @SafeVarags: 堆污染
- @FunctionlInterface: 是用来指定某一个接口必须是函数式接口
3. JDK的元Annotation
- @Retention (保留) 只能用于修饰Annotation定义,用于指定修饰的Annotation可以保留多长时间。
@Retention(value = RetentionPolicy.RUNTIME)当运行java程序时,程序可以通过反射获取该Annotation信息。 @Target也只能修饰一个Annotation定义,它用于指定被修饰的Annotation能用于修饰哪些程序单元。 @Target(ElementType.FIELD)只能修饰成员变量。 @Target(ElementType.METHOD)只能修饰方法。
@Documented用于指定被该元Annotation修饰的Annotation类被javadoc工具提取成文档
@Inherited元Annotation指定被它修饰的Annotation将具有继承性—-如果某个类使用了@Xxx注解修饰,则子类将自动被@Xxx修饰
4. 自定义Annotation
4.1 自定义Annotation步骤
- 定义新的Annotation类型使用@interface关键字,与定义一个接口非常相似
- 添加元Annotation, @Retention(RetentionPolicy.RUNTIME)—>当运行java程序时,程序可以通过反射来获取Annotation的信息,@Target—>只能修饰方法(ElementType.METHOD)
- Annotation的成员变量在Annotation定义中以无形参的方法形式来声明,该方法名和返回值定义了该成员变量的名字和类型.—>String sex() default “男”, 使用default为成员变量指定初始值.
- 在需要使用的方法上添加注解,@CustomAnnotation(userName = “zhm”, age = 26 ,sex = “女”)
- 通过反射获取注解信息
//当运行java程序时,程序可以通过反射来获取Annotation的信息
@Retention(RetentionPolicy.RUNTIME)
@Documented
// 只能修饰方法
@Target(ElementType.METHOD)
//定义新的Annotation类型使用@interface关键字,与定义一个接口非常相似
public @interface CustomAnnotation {
//Annotation的成员变量在Annotation定义中以无形参的方法形式来声明,该方法名和返回值定义了该成员变量的名字和类型
String userName();
int age();
//使用default为成员变量指定初始值
String sex() default "男";
}
public class UseAnnotation {
@CustomAnnotation(userName = "zhm", age = 26 ,sex = "女")
public void print(){
System.out.println("customAnnotation hello ");
}
}
public class TestAnnotation {
public static void main(String [] args){
//反射获取注解信息
Class useAnnotationClass = UseAnnotation.class;
Method[] methods = useAnnotationClass.getMethods();
for(Method m : methods){
CustomAnnotation annotation = m.getAnnotation(CustomAnnotation.class);
//返回该程序元素上存在的,指定类型的注解,如果该注解不存在返回null
if(annotation!=null){
int age = annotation.age();
String sex = annotation.sex();
String userName = annotation.userName();
System.out.println("age = "+age +" sex = " + sex + " userNme = " + userName);
}
}
}
}