JDK1.8之Annotation注解一基础篇

本文详细介绍了自定义注解的定义与使用,通过一个具体案例展示了如何利用注解处理器进行代码分析与操作,揭示了注解在实际开发中的重要作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

其实嘞,前面在玩aop的时候也有写过自定义注解来实现aop。今天就来系统学习一下注解。

一、定义注解

package org.ssm.king.test;

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CustomAnnotation {
    int id();

    String description() default "no description!";
}

这是一个简单自定义注解的定义。三种注解在之前有过讲解,在这就不再赘述,特别说一下,这三种注解再加上@Inherited注解,被称为元注解。这里要说说注解定义后的使用,下面写一个简单用例:

package org.ssm.king.annotationtest;

public class AnnotationTest {

    @CustomAnnotation(id = 100, description = "userName must be true")
    public boolean validateUserName(String userName) {
        return userName.matches("");
    }
}

看到这,我自己都想知道,注解的作用是什么呢?怎么感觉跟注释没什么两样啊!

二、注解处理器

与注解搭配使用,目的是为了让注解变得有用。这里会用到一些反射的东东。

package org.ssm.king.annotationtest;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class UseCaseTracker {
    public static void trackUseCase(List<Integer> useCase, Class<?> cl) {
        for (Method m : cl.getDeclaredMethods()) {
            CustomAnnotation customAnnotation = m.getAnnotation(CustomAnnotation.class);
            if (customAnnotation != null) {
                System.out.println("Found case:" + customAnnotation.id() + " " + customAnnotation.description());
                useCase.remove(new Integer(customAnnotation.id()));
            }
        }
        for (int i : useCase) {
            System.out.println("Warning : Missing use case - " + i);
        }
    }

    public static void main(String[] args) {
        List<Integer> userCase = new ArrayList<>();
        Collections.addAll(userCase, 100, 101, 102);
        trackUseCase(userCase, AnnotationTest.class);
    }
}

通过这个用例呢,就能看出,注解的其中一个用法。执行结果如下:

Found case:100 userName must be true
Warning : Missing use case - 101
Warning : Missing use case - 102

Process finished with exit code 0

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值