Annotation

1.注解是什么

对于Annotation,是Java5的新特性。Annotations提供一些本来不属于程序的数据,比如:一段代码的作者或者告诉编译器禁止一些特殊的错误。Annotations使用@annotation的形式应用于代码:类(class),属性(attribute),方法(method)等等。一个Annotation出现在上面提到的开始位置,而且一般只有一行,也可以包含有任意的参数。

2.内置注解

@Override对父类的方法重写

@Deprecated过时的,废弃的

@SuppressWarning 镇压报警信息

SuppressWarning需要添加参数进行使用

参数说明
deprecation使用了过时的类或者方法
unchecked执行了未检查的转换时的警告,例如当使用集合时没有用泛型来指定集合保存的类型
fallthrough使用Switch语句时发生case穿透
path在类路径、源文件路径等中有不存在的路径时的警告
serial当在可序列化的类上缺少serialVersionUID定义时的警告
finally任何fianlly子句不能正常完成时的警告
all关于以上所有情况的警告
//取消所有的警告
@SuppressWarnings("all")
//取消多种类型的警告
@SuppressWarnings(value = {"uncheck", "deprecation"})

@SuppressWarnings({"uncheck", "deprecation"})

3.元注解

元注解负责注解自定义注解

1.@Target

用于描述注解的使用范围

参数修饰范围
ElementType.PACKAGE
ElementType.TYPE类、接口、枚举、Annotation类型
ElementType.CONSTRUCTOR构造器
ElementType.FIELD
ElementType.METHOD方法
ElementType.LOCAL_VARIABLE局部变量
ElementType.PARAMETER参数
//表示该自定义注解只能使用在方法和域上
@Target(value = {ElementType.METHOD, ElementType.FIELD})
public @interface MyAnnotation {
}

2.@Retention

用于描述注解的生命周期

参数作用
RetentionPolicy.CLASS在源文件中有效
RetentionPolicy.SOURCE在class文件中有效
RetentionPolicy.RUNTIME在运行时有效,可以被反射机制读取

4.自定义注解

/**
 * @Target 表示自定义的Annotation可以使用在方法或者域上
 * */
@Target(value = {ElementType.METHOD, ElementType.FIELD})
/**
 * @Retention 表示自定义的Annotation不仅被保存在class文件中,jvm加载class文件后,仍然存在
 * */
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    /**
     * 使用Annotation时可使用的参数值,default为默认值
     * 当参数只有一个时可以命名为value这样可以使用@Annocation(参数值)的方法使用
     */
    String[] value() default {"sdf", "dfa"};
    int id() default 0;
}
 	/*
     * 不加参数名时默认使用value名的参数
     * */
    @MyAnnotation({"asdfa","dfadf"})
    public void study(){
    }
    /*
    * 定义多个参数中间用,隔开
    * */
    @MyAnnotation(value = {"dfaf", "adfasd"},id = 5)
    public void study1(){

    }

5.通过反射来解析注解

public class Test {
    public static void main(String[] args) {
        try {
            //通过类的全称获得对应类
            Class<?> cl = Class.forName("com.fxl.annotation.AnnotationTest");
            //获得该类下的study1()方法
            Method study = cl.getMethod("study1");
            //获得作用在该方法上的MyAnnotation类的注解
            MyAnnotation myAnnotation = study.getAnnotation(MyAnnotation.class);
           //输出该注解的id参数
            System.out.println(myAnnotation.id());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
}

结果图

在这里插入图片描述

个人笔记,有错误还请指出

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值