博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java注解Annotation使用
阅读量:4068 次
发布时间:2019-05-25

本文共 1856 字,大约阅读时间需要 6 分钟。

Java注解Annotation的使用

RuntimeAnnotation注解

package annotation;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.FIELD)public @interface RuntimeAnnotation {}

ClassAnnotation注解

package annotation;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Retention(RetentionPolicy.CLASS)@Target(ElementType.FIELD)public @interface ClassAnnotation {}

枚举类AnType中使用注解

package annotation;import java.lang.annotation.Annotation;import java.lang.reflect.Field;public enum AnType {    @RuntimeAnnotation    @ClassAnnotation    TYPE_TEST_1,    @ClassAnnotation    TYPE_TEST_2;    /**     * 注解使用:可以在运行时通过反射判断某字段是否有某注解进而进行一些操作     */    public boolean isRuntimeAnnotation(){        Field field = new Field();        try {            /**             * 通过反射获取该对象在枚举中的字段             */            field = this.getClass().getField(this.name());        } catch (Exception e) {        }        return isFieldAnnotated(field, RuntimeAnnotation.class);    }    /**     * 该field的注解中是否匹配输入的注解     */    private boolean isFieldAnnotated(Field field, Class
annotationClass) { if (field == null) { return false; } /** * annotations中有RuntimeAnnotation,但是没有ClassAnnotation * 因为RuntimeAnnotation被注解为Runtime,可以被反射出来 */ Annotation[] annotations = field.getAnnotations(); if(annotations == null || annotations.length == 0){ return false; } for (Annotation annotation : annotations) { if (annotation.annotationType().equals(annotationClass)) { return true; } } return false; }}

转载地址:http://khaji.baihongyu.com/

你可能感兴趣的文章
将file文件内容转成字符串
查看>>
循环队列---数据结构和算法
查看>>
优先级队列-数据结构和算法
查看>>
链接点--数据结构和算法
查看>>
servlet中请求转发(forword)与重定向(sendredirect)的区别
查看>>
Spring4的IoC和DI的区别
查看>>
springcloud 的eureka服务注册demo
查看>>
eureka-client.properties文件配置
查看>>
MODULE_DEVICE_TABLE的理解
查看>>
platform_device与platform_driver
查看>>
platform_driver平台驱动注册和注销过程(下)
查看>>
.net强制退出主窗口的方法——Application.Exit()方法和Environment.Exit(0)方法
查看>>
c# 如何调用win8自带的屏幕键盘(非osk.exe)
查看>>
build/envsetup.sh 简介
查看>>
C++后继有人——D语言
查看>>
Android framework中修改或者添加资源无变化或编译不通过问题详解
查看>>
linux怎么切换到root里面?
查看>>
linux串口操作及设置详解
查看>>
安装alien,DEB与RPM互换
查看>>
linux系统下怎么安装.deb文件?
查看>>