Java基础-注解

本文详细介绍了Java中的注解,包括其元数据特性、生命周期策略(SOURCE、CLASS、RUNTIME)、目标元素(如METHOD、FIELD等),并通过Todo接口和Author接口的使用实例展示了注解的处理过程。
摘要由CSDN通过智能技术生成

概述

  • 注解:元数据
    • 注解本身仅仅是元数据,和业务逻辑无关,业务逻辑是注解的用户来实现的,比如JVM也是这样的一个用户
  • 元注解:注解的注解
    • @Documented:注解是否包含在Java Doc中
    • @Retention:注解生命周期
      • RetentionPolicy.SOURCE:编译阶段丢弃,不进入字节码;如Override,SupressWarnings
      • RetentionPolicy.CLASS:默认,类加载时丢弃,字节码处理过程中有用
      • RetentionPolicy.RUNTIME:始终不丢弃,运行期通过反射获取
    • @Target:注解用于什么地方
      • 如不明确指出,则该注解可放在任何地方
      • ElementType.TYPE:类,接口,或enum
      • FIELD
      • METHOD
      • PARAMETER
      • CONSTRUCTOR
      • LOCAL_VARIABLE
      • ANNOTATION_TYPE:另一个注解
      • PACKAGE
    • @Inherited:是否允许被子注解继承

例子

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface Todo{
    public enum Priority {LOW, MEDIUM, HIGH}
    public enum Status {STARTED, NOT_STARTED}
    String author() default "Yash";
    Priority priority default Priority.LOW;
    Status status() default Status.NOT_STARTED;
}

@Todo(priority=Todo.Priority.MEDIUM, author="Yashwant", status=Todo.Status.STARTED)
public void method1() {
    // xxx
}

@interface Author {
    String value();
}

@Author("Yashwant")
public void method2() {
    // xxx
}

注解处理

Class businessLogicClass = BusinessLogic.class;
for(Method method : businessLogicClass.getMethods()) {
    Todo todoAnnotation = (Todo)method.getAnnotation(Todo.class);
    if(todoAnnotation != null) {
        System.out.println("Method Name: " + method.getName());
        System.out.println("Author: " + todoAnnotation.author());
        System.out.println("Priority: " + todoAnnotation.priority());
        System.out.println("Status: " + todoAnnotation.status());
    }
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Eddy咸鱼

感谢大佬加鸡蛋~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值