Java注解

10.注解

  -Annotation是从JDK5.0开始引进的新技术

  -作用:对程序做出解释;可以被其它程序(比如:编译器)读取

  -格式:注解是以@注释名在代码中存在,还可以添加一些参数值(eg:@SuppressWarning(value="unchecked"))

  -使用场合:在package、class、method、field等上面,相当于添加了额外的辅助信息,通过反射机制对这些元数据进行访问。

10.1内置注解

  -@Override:定义在java.lang.Override中,此注释只适用于修辞方法表示一个方法声明打算重写超类中的另一个方法声明

  -@Deprecated:定义在java.lang.Deprecated中,此注释可用于修饰方法、属性、类;不鼓励使用

  -@SupressWarning("参数"):用来抑制编译时的警告信息;需要提供参数

 package com.annotation;
 ​
 //什么是注解
 public class Demo01_Test extends Object{
 ​
     //重写的注解
     @Override
     public String toString() {
         return super.toString();
    }
 }

10.2元注解

-作用:负责注解其它注解

  -@Target:用于描述注解的使用范围

  -@Retention:表示需要在什么级别保存该注释信息,用于描述注解的生命周期(SOURCE<CLASS<RUNTIME)

  -@Document:说明该注解将包含在javadoc

  -@Inherited:说明子类可以继承父类中的该注解

 package com.annotation;
 ​
 import java.lang.annotation.*;
 ​
 //测试元注解
 @MyAnnotation
 public class Demo02_Test {
     @MyAnnotation
     public void test(){
 ​
    }
 }
 ​
 //定义一个注解
 @Target(value = {ElementType.METHOD,ElementType.TYPE})  //Target 表示我们的注解可以用在哪些地方
 @Retention(value = RetentionPolicy.RUNTIME)  //表示注解在什么地方还有效
     //runtime > class > sources
 @Documented //生成javadoc文档
 ​
 @Inherited //子类可以继承父类的注解
 @interface MyAnnotation{
 ​
 }

10.3自定义注解

-使用@interface自定义注解,自动继承了java.lang.annotation.Annotation接口

-分析:

  @interface 用来声明一个注解,格式:public @interface 注解名 {定义内容}

  每一个方法实际上是声明了一个配置参数  

  方法的名称就是参数的名称

  返回值类型就是参数的类型(class、String、enum)

  可以通过default来声明参数的默认值

  如果只有一个参数成员,一般参数名为value

  注解元素必须要有值,定义注解元素时,经常使用空字符串、0作为默认值

 package com.annotation;
 ​
 import java.lang.annotation.ElementType;
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 import java.lang.annotation.Target;
 ​
 //自定义注解
 public class Demo03_Test {
 ​
     @MyAnnotation2(name = "Joey",schools = {"二民院"})
     public void test(){
 
    }
 }
 ​
 @Target({ElementType.TYPE,ElementType.METHOD})
 @Retention(RetentionPolicy.RUNTIME)
 @interface MyAnnotation2{
     //注解的参数:参数类型 + 参数名();
     String name() default "";//default 设置默认值
     int age() default 0;
     int id() default -1; //如果默认值为-1,代表不存在
 ​
     String[] schools() default {"北方民族大学"};
 }

 

原文地址:https://www.cnblogs.com/joey-413/p/13234869.html