自定义注解(一)
来源:互联网 发布:网络毛笔字 编辑:程序博客网 时间:2024/06/14 09:44
以前都是使用各种注解,最近的项目中,使用到了自定义注解,在这里记录一下。
自定义注解很简单,只要使用@interface就可以了
package org.ygy.demo.annotation;public @interface Hello{String value();String info();}
下面在介绍一下,在自定义注解时会用到的
@Target:限定注解生效的对象范围,使用ElementType枚举
public enum ElementType { /** Class, interface (including annotation type), or enum declaration */ TYPE, /** Field declaration (includes enum constants) */ FIELD, /** Method declaration */ METHOD, /** Parameter declaration */ PARAMETER, /** Constructor declaration */ CONSTRUCTOR, /** Local variable declaration */ LOCAL_VARIABLE, /** Annotation type declaration */ ANNOTATION_TYPE, /** Package declaration */ PACKAGE}
@Retention : 保持机制,保持策略有RUNTIME,CLASS,SOURCE
package java.lang.annotation;public enum RetentionPolicy { /** * 编译器要丢弃的注解。 */ SOURCE, /** * 编译器将把注解记录在类文件中,但在运行时 VM 不需要保留注解。 */ CLASS, /** * 编译器将把注解记录在class文件中,在运行时 VM 将保留注解,可以通过反射读取。 */ RUNTIME}
@Inherited : 表示子类可以继承该注解
自定义注解时,可以不指定参数,也可以指定参数
1.没有参数
@Documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.ANNOTATION_TYPE)public @interface Inherited {}2.只有一个参数value时,可以指明value=,也可以保持默认
@Inherited@Target({ElementType.FIELD})@Retention(value = RetentionPolicy.RUNTIME)public @interface Hello{String value();String info();}
@Inherited@Target({ElementType.FIELD})@Retention(RetentionPolicy.RUNTIME)public @interface Hello{String value();String info();}
3.参数时数组
可以使用 {}
@Documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.ANNOTATION_TYPE)public @interface Target { ElementType[] value();}
@Target({ElementType.FIELD})
4.使用默认值
@Inherited@Target({ElementType.FIELD})@Retention(value = RetentionPolicy.RUNTIME)public @interface Hello{String value();String info() default "haha";}
只要使用default就可以了,使用默认值之后,可以在调用该注解时,不给该属性赋值
PS:在使用@Inherited注解时,说是子类可以继承该注解,但是自己尝试之后,发现好像没有用,有待研究。
哈,发现一片博客,讲到了,可以看下:
子类是否继承父类的 annotation - Inherited
自定义注解系列:
自定义注解(一)
自定义注解(二)
- 自定义注解(一)
- 注解(Annotation)自定义注解(一)
- Java:Annotation 浅析(一 )自定义注解
- (A6,一)java自定义注解
- 自定义Java注解(一)
- 自定义注解【一】
- 自定义注解之编译时注解(RetentionPolicy.CLASS)(一)
- 自定义注解之编译时注解(RetentionPolicy.CLASS)(一)
- 自定义注解的学习(一)
- 自定义注解整理 篇一
- 注解(Annotation)自定义注解
- java自定义注解及注解使用(注解学习一)
- Java注解(一):注解介绍及自定义注解入门
- Java Annotation详解+自定义java注解(一)
- Spring mvc的自定义注解权限拦截器(一)
- 自定义注解(二)
- 自定义Annotation(注解)
- 自定义注解(Annotation)
- Linux下各种主要文件系统的读写性能测试
- HDU 2602 01背包中两种写法
- 解决struts2 属性参数乱码问题
- 2013.9.9杂感
- Redis--利用JAVA操作Redis
- 自定义注解(一)
- MapReduce源码分析总结
- 用Intellij IDEA创建新项目的时候报错cannot find resource directory for module
- 程序猿的小资生活
- IXMLDOMDOCUMENT 的appendchild,removechild返回E_FAIL
- poj——1152——An Easy Problem!
- 内存中堆栈与数据结构中堆栈
- POJ 1724
- 通过rowid得到数据块的相关信息