栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java自定义注解

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java自定义注解

引入依赖:

 
    org.reflections
    reflections
    0.10.2
 

定义注解:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    String value() default "";
}

创建3个类并使用自定义注解:

@MyAnnotation("been")
public class Been {
}
@MyAnnotation("小猫咪")
public class Cat {
}

@MyAnnotation("")
public class Dog {
}

利用反射解析注解:

public class MyAnnotationUtil {

    public static final Map map;

    static {
        map = new LinkedHashMap<>();
        //扫描的包
        String packages = "com.cc.springboot.annotation";
        Reflections fs = new Reflections(packages);
        Set> sets = fs.getTypesAnnotatedWith(MyAnnotation.class);
        for (Class s : sets) {
            MyAnnotation annotation = s.getAnnotation(MyAnnotation.class);
            String value = annotation.value();
            if ("".equals(value)) {
                String[] split = s.getName().split("\.");
                String name = split[split.length - 1];
                map.put(name, s.getName() + "-->此类使用了自定义注解");
            } else {
                map.put(value, s.getName() + "-->此类使用了自定义注解");
            }

        }
    }

    public static void main(String[] args) {
        Map maps = MyAnnotationUtil.map;
        System.out.println(maps);
    }
}

运行结果:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/956158.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号