注解 --------- (笔记)

注解 --------- (笔记)

1.元注解

  1. @Deprecated 过时: 用于过时的类、方法、成员变量等

  2. @Override: 覆盖父类方法

  3. @SuppressWarning:阻止警告

2.元注解

  1. @Target : 用于描述注解使用的范围 (可以在哪些地方使用到注解)

TYPE,FIELD,METHOD,PARAMETER,CONSTRUCTOR,LOCAL_VARIABLE,

ANNOTATION_TYPE,PACKAGE,TYPE_PARAMETER,TYPE_USE

import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@MyAnnotation
public class Test {
    
    
    @MyAnnotation
    public void test(){
    
    
    }
}
//表示可以用在哪些地方
@Target(value = {
    
    ElementType.METHOD,ElementType.TYPE})
@interface MyAnnotation{
    
    
}
  1. @Retention:描述注解的生命周期 表示需要在什么级别保存该注释信息

(SOURCE < CLASS < RUNTIME)

//表示什么时候还有效
@Retention(value = RetentionPolicy.RUNTIME)
@interface MyAnnotation{
    
    
}
  1. @Document: 说明该注解该被包含在javadoc中

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

3. 自定义注解

@MyAnnotation1("test")
public class Test {
    
    
    @MyAnnotation
    public void test(){
    
    
    }
}
@Target(value = {
    
    METHOD,TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
@interface MyAnnotation{
    
    
    //注解的参数:参数类型 参数名()
    //默认值 default ""
    String name() default "";
    int id() default -1;//默认为-1代表不存在
    String[] friends() default {
    
    "test1","test2"};
}
@Target(value = {
    
    METHOD,TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
@interface MyAnnotation1{
    
    
    String value();//只有一个值用value命名
}

猜你喜欢

转载自blog.csdn.net/qq_41454682/article/details/112184092