通过反射获取自定义注解的值实践

自定义注解

Java自带的注解的作用是帮助我们减少错误,比如Overwrite就提醒我们必须对该方法进行重写,或继承父类的实现。@Deprecated提示我们这个方法已经被弃用了,有更好的替代者。

自定义注解也有类似的作用,但是更重要的实现是和反射配合使用,是各种java框架的灵魂,主要的作用是实现将我们的写的类根据不同的注解进行分类管理,并且还能将我们写的类和注解的信息进行动态的绑定,让我们实现更加强大的功能,而这些功能是通过框架本身进行管理的,无需我们去操心,我们只要关系注解在框架中的作用就可以了,一个字就是🐂🍺

自定义注解和读取自定义注解的例子

package com.jstar;

import javax.annotation.Resource;
import java.lang.annotation.*;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Jstar
 * @version 1.0
 * @date 2021/7/1 11:10 下午
 */
public class ReflectTest {
    @MyAnnotation(name = "Tom")
    public void test() {
    }

    @Deprecated
    @MyAnnotation(name = "jam")
    public void test2() {

    }


    public static void main(String[] args) throws ClassNotFoundException {
        // get Class object
        ReflectTest reflectTest = new ReflectTest();
        Class<?> aClass = reflectTest.getClass();

        // get annotation from object.method
        Method[] methods = aClass.getMethods();
        HashMap<String, String> MethodAnnotations = new HashMap<>();

        for (Method method : methods) {
            String annotation = "";
            //  filter condition of My own annotation
            if (method.isAnnotationPresent(MyAnnotation.class)) {
                MyAnnotation methodAnnotation = method.getAnnotation(MyAnnotation.class);
                annotation = methodAnnotation.name();
                MethodAnnotations.put(method.getName(), annotation);
            }

        }

        // Stream out
        MethodAnnotations.forEach((s, v) -> System.out.println( "Method name " + s + "annotation name " +  v));
        
        
        //  entrySet use test
        for (Map.Entry<String, String> stringStringEntry : MethodAnnotations.entrySet()) {
            System.out.println(stringStringEntry.getKey() + stringStringEntry.getValue());
        }
    }

    @Target({ElementType.METHOD, ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @interface MyAnnotation {

        // 参数
        String name();

    }

}

输出

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值