怎么自己写一个像spring中的高大上的注解--思路

本文介绍了一种使用自定义注解进行方法级别的元数据标记的方法,并通过实例演示了如何创建自定义注解、应用注解到方法上以及如何编写解析器来读取这些注解信息。

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

第一步:

需要自己建一个注解类

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation {
    String TYPE() default MyAnnotation.FAnno;
    public static final String FAnno = "F";
    public static final String SAnno = "A";
    public static final String TAnno = "T";
}

第二步:

写一个测试类,加自己的注解

public class TestClass {

    @MyAnnotation(TYPE = MyAnnotation.TAnno)
    public void eat(){
        System.out.println("我在吃饭");
    }

    @MyAnnotation
    public void watch(){
        System.out.println("我在看电视");
    }

}

第三步:
写一个解析注解的类
public class ExplainMyAnnotation {

    public void explain(Method method){
        Annotation[] annotations = method.getAnnotations();
        for (Annotation anno : annotations){
            if (anno instanceof MyAnnotation){
                //do sth
                MyAnnotation myAnnotation = (MyAnnotation) anno;
                System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"+myAnnotation.TYPE());
                System.out.println("................................"+myAnnotation.toString());
            }
        }
    }

}

第四步:
将带注解的类和解析注解的类关联起来
public class TestAnnotation {

    public static void main(String[] args){
        ExplainMyAnnotation e = new ExplainMyAnnotation();
        TestClass t = new TestClass();
        Method[] m = t.getClass().getMethods();
        for(int i=0; i<m.length; i++){
            System.out.println("第"+i+"次");
            e.explain(m[i]);
        }
    }
}

这只是一个思路,代码写的有点垃圾,哪位大神有更好的办法,希望不吝赐教。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值