自定义注解与提取注解学习

2017-09-13  本文已影响75人  走在冷风中吧

上一篇: java 注解学习
上篇文章中学习了系统内置注解与元注解(@Retention, @Target, @Inherited, @Document), 元注解可帮助我们进行一些自定义注解, 接下来我们学习如何自定义注解.

定义自定义注解

自定义注解与定义接口很相似, 只是将 interface换成@interface即可.

public @interface MyFirstAnnotation {
}
如果自定义注解上没有添加元注解, 则默认该注解可以用于类,接口,方法等
public @interface MyFirstParamAnnotation {
    String value();
}
参数可以有一个或者多个, 一个的情况下一般参数名都为 value(因为涉及到注解取值时候的简写, 默认习惯而已) 
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyFirstParamAnnotation {
    String value();
}
@Retention 为运行时可见, 可以使用反射获取注解
@Target 表示该注解为类注解, 指定了注解的修饰位置

自定义注解的使用

自定义注解的使用很简单, 根据定义好的注解以及需求, 在需要使用注解的上@+注解名

@MyFirstParamAnnotation("user")
public class User {
    
}

然鹅, 这样使用没有什么实质性的作用, 因为没有对注解进行提取, 所有在代码效果上添加注解并不作用, 接下来我们学习如何提取注解,使自定义注解变得有意义.

提取自定义注解

自定义注解的提取主要依靠的是AnnotatedElement 类,位于java.lang.reflect下,
以下为源码:

public interface AnnotatedElement {
    default boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
        throw new RuntimeException("Stub!");
    }

    <T extends Annotation> T getAnnotation(Class<T> var1);

    Annotation[] getAnnotations();

    Annotation[] getDeclaredAnnotations();

    default <T extends Annotation> Annotation getDeclaredAnnotation(Class<T> annotationClass) {
        throw new RuntimeException("Stub!");
    }

    default <T extends Annotation> T[] getDeclaredAnnotationsByType(Class<T> annotationClass) {
        throw new RuntimeException("Stub!");
    }

    default <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) {
        throw new RuntimeException("Stub!");
    }
}

从源码中我们能看到这么几个方法,isAnnotationPresent , getAnnotation , getAnnotations , getDeclaredAnnotations 使我们提取注解的关键方法

方法名 参数 返回值 作用
isAnnotationPresent annotationClass 布尔值 检测该元素是否被这个注解类注解过
getAnnotation annotationClass 注解类 获得这个注解类对应的注解对象
getAnnotations 所有的注解类 获得该元素上的所有注解类数组, 没有的话返回长度为0的数组
getDeclaredAnnotations 所有的注解类 同上, 但是返回的数组中不包括继承的注解

很多强大的第三方数据库都是通过注解的方式实现的,现在我们举一个简单的例子去提取注解

Table.class 定义好注解类

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Table {
    String value();
}

在ORM中一般把表映射为实体类,所以表注解的修饰类型这里设为ElementType.TYPE代表可修饰类类型

user.class 使用注解类Table修饰

@Table("user")
public class User {
    private String name;
}

提取注解:

.....

    public void getAnnotation(){
        User user = new User();
        if (user.getClass().isAnnotationPresent(Table.class)){
            Table table = user.getClass().getAnnotation(Table.class);
            String value = table.value();
            System.out.print("table's value is " + value);
        }
    }
.....
输出结果为 table's value is user

本文为自己的学习笔记, 很多地方可能写的不是很对, 作为学习成果保存下来, 日后发现不足的地方会进行及时更新!~
END...

上一篇下一篇

猜你喜欢

热点阅读