Java---注解

1.什么是注解

作用:不是程序本身 , 可以对程序作出解释.(这一点和注释(comment)没什么区别) ;可以被其他程序(比如:编译器等)读取
格式:以"@注释名"在代码中存在的 , 还可以添加一些参数值
如:@SuppressWarnings(value=“unchecked”)
在哪里使用 :可以附加在package , class , method , field 等上面 , 相当于给他们添加了额外的辅助信息, 我们可以通过反射机制编程实现对这些元数据的访问。

2.内置注解

3个内置注解:
@Override - 检查该方法是否是重载方法。如果发现其父类,或者是引用的接口中并没有该方法时,会报编译错误。
@Deprecated - 标记过时方法。如果使用该方法,会报编译警告。表示 鼓励程序员使用这样的元素 , 通常是因为它很危险或者存在更好的选择
@SuppressWarnings - 指示编译器去忽略注解中声明的警告。与前两个注释有所不同,你需要添加一个参数才能正确使用,这些参数都是已经定义好了的, 我们选择性的使用。
@SuppressWarnings(“all”)
@SuppressWarnings(“unchecked”) @SuppressWarnings(value={“unchecked”,“deprecation”})

public class Test1{
    public void main(String[] args) {
       test();
       toString();
    }

    //标注这个方法,过时的,或者危险的,不建议使用,但是可以使用!
    @Deprecated
    public int test(){  //不建议使用
        System.out.println("aaaaaa");
        return 1;
    }

    public String hello(){ //没有被使用
       List list = new ArrayList<>();
       return "hello,world!";
    }

    @Override //标注了这个注解,就代表子类重写了父类的方法,而且必须保持一致
    public String toString() {
        return "Test1{}";
    }
}

3.元注解

元注解的作用就是负责注解其他注解 , Java定义了4个标准的meta-annotation类型,他们被用来 提供对其他annotation类型作说明.
@Target , @Retention , @Documented , @Inherited
@Target : 用于描述注解的使用范围(即:被描述的注解可以用在什么地方)
@Retention : 表示需要在什么级别保存该注释信息 , 用于描述注解的生命周期
@Document:说明该注解将被包含在javadoc中
@Inherited:说明子类可以继承父类中的该注解

public class Test2 {

    private int age;

    @MyAnnotation
    public int getAge() {
        return age;
    }
}
//如何自定义注解呢?  @interface 注解名,注意和 interface的区别

//除了这四个注解之外的所有注解,都叫做自定义注解!

@Target(ElementType.METHOD) //表示我这个注解,能够注解谁!  方法,字段,类
@Retention(RetentionPolicy.RUNTIME) //自定义注解我们都会使用 RetentionPolicy.RUNTIME 在运行时生效
@Documented //表示L可以在Javadoc中生成信息,没什么用!
@Inherited //表示子类可以继承父类的注解,一般也不用!
@interface MyAnnotation{
}

4.自定义注解

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

  • @ interface用来声明一个注解
    格式 : public @ interface 注解名 { 定义内容 }
  • 其中的每一个方法实际上是声明了一个配置参数.
  • 方法的名称就是参数的名称.
  • 返回值类型就是参数的类型 ( 返回值只能是基本类型,Class , String , enum ).
  • 可以通过default来声明参数的默认值
  • 如果只有一个参数成员 , 一般参数名为value
  • 注解元素必须要有值 , 我们定义注解元素时 , 经常使用空字符串,0作为默认值
public class Test3 {
//注解可以显示赋值,如果没有赋值,我们必须给出注解赋值
    @MyAnnotation2(name = "yang",age = 18 ,id = -1,schools = "123")
    public  void test(){
        
    }
    private int age;
    @MyAnnotation3("aaa")
    public int getAge() {
        return age;
    }

}

@Target(value={ElementType.METHOD}) //在类上方法上
@Retention(value = RetentionPolicy.RUNTIME)
@interface MyAnnotation2{
    String name() default "";
    int age() default 0;
    int id() default -1; // String indexOf("abc")   -1, 找不到,不存在
    String[] schools();

}

@Target(value={ElementType.METHOD})
@Retention(value = RetentionPolicy.RUNTIME)
@interface MyAnnotation3{
    String[] value(); //只有一个参数的一般名字叫做value, 可以省略!

}
发布了39 篇原创文章 · 获赞 1 · 访问量 556

猜你喜欢

转载自blog.csdn.net/love_to_share/article/details/103472164