JAVA 注解

Annotation的作用

  1.   标记,用于告诉编译器一些信息
  2.   编译时动态处理,如动态生成代码
  3.   运行时动态处理,如得到注解信息

Annotation作用范围

        可以附加在Package、Class、methord、field等上面,相当于给他们添加额外的辅助信息。

内置注解

  • @Deprecated 已过期,表示方法是不被建议使用的(可用于修饰属性、方法、类)
  • @Override 重写,标识覆盖它的父类的方法(只能修饰方法)
  • @SuppressWarnings 压制警告,抑制警告

示例代码:

import java.util.ArrayList;
import java.util.List;

public class Main extends Object {

    @Override
    public String toString(){
        return super.toString();
    }

    @Deprecated
    public void  test(String test){
        System.out.println(test);
    }

    @SuppressWarnings("all")
    public void test2(){
        List list = new ArrayList();
    }
}

元注解

1.@Target

        用于描述注解的范围,即注解在哪用。它说明了Annotation所修饰的对象范围:Annotation可被用于 packages、types(类、接口、枚举、Annotation类型)、类型成员(方法、构造方法、成员变量、枚举值)、方法参数和本地变量(如循环变量、catch参数)等。取值类型(ElementType)有以下几种:

public enum ElementType {
    /** Class, interface (including annotation type), or enum declaration */
    TYPE,

    /** Field declaration (includes enum constants) */
    FIELD,

    /** Method declaration */
    METHOD,

    /** Formal parameter declaration */
    PARAMETER,

    /** Constructor declaration */
    CONSTRUCTOR,

    /** Local variable declaration */
    LOCAL_VARIABLE,

    /** Annotation type declaration */
    ANNOTATION_TYPE,

    /** Package declaration */
    PACKAGE,

    /**
     * Type parameter declaration
     *
     * @since 1.8
     */
    TYPE_PARAMETER,

    /**
     * Use of a type
     *
     * @since 1.8
     */
    TYPE_USE
}

2.@Retention

        定义注解的保留策略,

  • SOURCE : 保留在源文件
  • CLASS : 保留在class文件
  • RUNTIME : 保留在运行时
public enum RetentionPolicy {

    SOURCE,
    CLASS,
    RUNTIME
}

3.@Document

        说明该注解将被包含在javadoc中。

4.@Inherited

       说明子类可以继承父类中的该注解

自定义注解

示例代码:

import java.lang.annotation.*;

/**
 * @ClassName Annotation
 * @Author Bysen
 * @Date 2020/12/27 18:54
 * @Description TODO
 * @Version 1.0
 **/
public class Annotation{
    @MyAnnotation(name = "bysen")
    public void test(){
        System.out.println("");
    }
}
@Target(value = {ElementType.METHOD})
@Retention(value = RetentionPolicy.RUNTIME)
@Documented
@Inherited
@interface MyAnnotation{
    String name() default "";
    int age() default 0;
}

注意:如果注解中只有一个参数时建议将其命名为 value,这样在使用注解时可以直接传参。

参考:

        https://www.cnblogs.com/ren9ie/p/10962509.html

        https://blog.csdn.net/xdzhouxin/article/details/79754429

        https://blog.csdn.net/b1303110335/article/details/105338986/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值