以前都是使用各种注解,最近的项目中,使用到了自定义注解,在这里记录一下。
自定义注解很简单,只要使用@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
自定义注解系列: