Think in java笔记: Annotation

Think in java笔记: Annotation

  1. Annotation是什么?
    Annotation是一种元数据信息,很奇怪的想起来了AspectJ的AOP,就是在方法、package等元素上加上一些标记,然后再自定负责自己的annotation,实现功能。和interface差不多,但是可以有默认值。

  2. 如何定义一个annotation

    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface Test {
    
    }

    定义annotation还需要meta-annotation:@target@Retention

    • @target:定义在哪使用这个annotation(比如说成员变量或方法)
    • @Rentention:定义什么时候可用,SOURCE 还是CLASS, 还是RUNTIME。

    这样不包含任何element的annotation,被称为marker annotation.

  3. Meta-annotations

    nameDescription
    @Target可以使用的ElementType类中的变量
    @Rententionannotation信息保留多久,具体的类在RetentionPolicy
    @Documented在javadocs中包含此annotation的信息
    @Inherited允许所有子类继承它们的父annotation
  4. annotation processors(annotation执行)
    如果没有工具来读取annotation,annotations几乎就和评论就一样。一个重要的部分就是创建和使用annotation processors. Java提供了反射的方法来实现annotation processors.还提供了apt用来解析source code.

    public class UseCaseTracker {
    
        public static void trackUseCases(List<Integer> useCases, Class<?> cl){
            for(Method m : cl.getDeclaredMethods()){
                UseCase uc = m.getAnnotation(UseCase.class);
                if(uc != null){
                    System.out.println("Found Use Case:" + uc.id() + " " + uc.description());
                    useCases.remove(new Integer(uc.id()));
                }
            }
            for(int i : useCases){
                System.out.println("Warning: Missing use case-" + i);
            }
        }
    
        public static void main(String[] args) {
            List<Integer> useCases = new ArrayList<Integer>();
            Collections.addAll(useCases, 47, 48, 49, 50);
            trackUseCases(useCases, PasswordUtils.class);
        }
    }
  5. Annotation Value限制

    • compiler对value有限制要求的。没有任何Element可以拥有一个没有指定的value。这意味着elements元素必须拥有默认值或者使用的时候赋值。
    • 任何基本类型必须赋值,不能使用null。意味着defaut或者赋值的时候,就必须使用一个确定的值。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值