反射与注解

自定义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();
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值