自定义Annotation,类似于接口
@Documented
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface MyAnnotation{
/** 注解成员的定义:同接口方法定义,不能有参数,成员类型要求为基本数据类型、String、Class、枚
* 举、其他的注解及以上类型的数组,可以定义默认值,无默认值在使用注解时必须指定具体值
*/
String title() default "hello";
int num() default 1;
}
- @interface:声明MyAnnotation是一个注解
- @Documented:使该注解出现在JavaDoc中
- @Target:指定该注解可以使用的位置,可以定义多个ElementType
public enum ElementType {
/** 类, 接口 (包括注解类型), 或枚举类 */
TYPE,
/** 字段 (包括枚举常量) */
FIELD,
/** 方法 */
METHOD,
/** 形参 */
PARAMETER,
/** 构造函数 */
CONSTRUCTOR,
/** 局部变量 */
LOCAL_VARIABLE,
/** 注解类型 */
ANNOTATION_TYPE,
/** 包 */
PACKAGE,
/** Type parameter declaration @since 1.8 */
TYPE_PARAMETER,
/** Use of a type @since 1.8 */
TYPE_USE
}
- @Retention:指定注解保留策略
public enum RetentionPolicy {
/** 注解将被编译器丢弃,仅用于编译时 */
SOURCE,
/** 注解将被编译器记录在字节码文件中,但不会在运行时被虚拟机保留,该类型为默认选项 */
CLASS,
/** 记录在字节码文件中并且在运行时会被虚拟机保留,可以被反射读取 */
RUNTIME
}
- @Inherited:声明该注解是否有继承能力。使用该注解的类的子类也拥有该注解
反射获取注解成员
static class Person {
@MyAnnotation(title = "world")
public static void test() throws NoSuchMethodException {
Method method = Person.class.getDeclaredMethod("test");
if (method.isAnnotationPresent(MyAnnotation.class)) {
// 获取方法指定类型注解
MyAnnotation myAnnotation = method.getDeclaredAnnotation(MyAnnotation.class);
System.out.println(myAnnotation.title());
}
System.out.println("=====================");
Annotation[] annotations = method.getAnnotations();
for (Annotation myAnnotation : annotations) {
if (myAnnotation instanceof MyAnnotation) {
MyAnnotation myAnno = (MyAnnotation) myAnnotation;
System.out.println(myAnno.title());
}
}
}
}
public static void main(String[] args) throws NoSuchMethodException {
Person.test();
}