JavaSE之注解(Annotation)

什么是注解?

1.Annotation是JDk5.0开始引入的新技术
2.Annotation的作用:
不是程序本身,但是可以对解释做出程序(这一点和注释没有区别)
可以被其他程序(比如:编译器等)读取。
3.Annotation格式:
@注解名(可以传递参数)
4.Annotation可是使用的地方:
package、class、method、Filed等上面,相当于给他们添加了额外的辅助信息,我们可以通过反射机制编程实现对这些元注解的访问。

内置注解

1.@Override:表示方法的重写
2.@Deprecated:表示方法或者类有危险警告不建议使用。
3.@SuppressWarnings:抑制编译时的警告信息

代码演示:

public class Demo {
    
    
    //重写方法
    @Override
    public String toString() {
    
    
        return "Demo{}";
    }

    public static void main(String[] args) {
    
    
        /*
        *  @Deprecated
    public int getDate() {
        return normalize().getDayOfMonth();
    }*/
        //危险警告不建议使用
      new Date().getDate();
    }
    //抑制编译时的警告
    @SuppressWarnings("All")
    public static void haha(){
    
    

    }
}

元注解

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

代码演示:

public @interface Target {
    
    
    /**
     * Returns an array of the kinds of elements an annotation type
     * can be applied to.
     * @return an array of the kinds of elements an annotation type
     * can be applied to
     */
    ElementType[] value();
}

public @interface Retention {
    
    
    /**
     * Returns the retention policy.
     * @return the retention policy
     */
    RetentionPolicy value();
}

public @interface Documented {
    
    
}

public @interface Inherited {
    
    
}


自定义注解

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

  1. @ interface用来声明一个注解 , 格式 : public @ interface 注解名 { 定义内容 }
  2. 其中的每一个方法实际上是声明了一个配置参数. ü 方法的名称就是参数的名称.3.
  3. 返回值类型就是参数的类型 ( 返回值只能是基本类型,Class , String , enum ).
  4. 可以通过default来声明参数的默认值
  5. 如果只有一个参数成员 , 一般参数名为value
  6. 注解元素必须要有值 , 我们定义注解元素时 , 经常使用空字符串,0作为默认值 .

代码演示:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
@Documented
@Inherited
 public  @interface  Haha{
    
    
    String[] value();
 }

猜你喜欢

转载自blog.csdn.net/weixin_42093672/article/details/103462548
今日推荐