Java Annotation注解

来源:互联网 发布:数据可视化工作 编辑:程序博客网 时间:2024/06/03 18:13

Java Annotation注解、

  1. J2SE5.0版本在 java.lang.annotation提供了四种元注解,专门注解其他的注解:

@Documented –注解是否将包含在JavaDoc中
@Retention –什么时候使用该注解
@Target? –注解用于什么地方
@Inherited – 是否允许子类继承该注解

  1. @Documented–一个简单的Annotations标记注解,表示是否将注解信息添加在java文档中。
/*** 元注解被@Documented修饰,表示它本身也会被文档化。@Retention元注解的值* RetentionPolicy.RUNTIME表示@Documented这个注解能保留到运行时* @Target元注解的值ElementType.ANNOTATION_TYPE表示@Documented这个注解只能够用来描述注解类型。*/@Documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.ANNOTATION_TYPE)public @interface Documented {}
  1. @Retention– 定义该注解的生命周期。
@Retention(RetentionPolicy.RUNTIME)public @interface Developer {    String value();}

RetentionPolicy.SOURCE – 在编译阶段丢弃。这些注解在编译结束之后就不再有任何意义,所以它们不会写入字节码。@Override, @SuppressWarnings都属于这类注解。
RetentionPolicy.CLASS – 在类加载的时候丢弃。在字节码文件的处理中有用。注解默认使用这种方式。
RetentionPolicy.RUNTIME– 始终不会丢弃,运行期也保留该注解,因此可以使用反射机制读取该注解的信息。我们自定义的注解通常使用这种方式。

  1. @Target – 表示该注解用于什么地方。如果不明确指出,该注解可以放在任何地方。以下是一些可用的参数。需要说明的是:属性的注解是兼容的,如果你想给7个属性都添加注解,仅仅排除一个属性,那么你需要在定义target包含所有的属性。
    ElementType是一个枚举类型,它可以取以下值:
    TYPE:表示可以用来注解类、接口、注解类型或枚举类型;
    PACKAGE:可以用来注解包;
    PARAMETER:可以用来注解参数;
    ANNOTATION_TYPE:可以用来注解 注解类型;
    METHOD:可以用来注解方法;
    FIELD:可以用来注解属性(包括枚举常量);
    CONSTRUCTOR:可以用来注解构造器;
    LOCAL_VARIABLE:可用来注解局部变量。
@Documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.ANNOTATION_TYPE)public @interface Target {    ElementType[] value();}
  1. @Inherited – 定义该注释和子类的关系
    表明被修饰的注解类型是自动继承的。具体解释如下:若一个注解类型被Inherited元注解所修饰,则当用户在一个类声明中查询该注解类型时,若发现这个类声明中不包含这个注解类型,则会自动在这个类的父类中查询相应的注解类型,这个过程会被重复,直到该注解类型被找到或是查找完了Object类还未找到。
@Documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.ANNOTATION_TYPE)public @interface Inherited {}

如果注解中只有一个属性,可以直接命名为“value”,使用时无需再标明属性名。

  1. 自定义注解
@Documented@Retention(RetentionPolicy.CLASS)@Target(ElementType.METHOD)@Inheritedpublic @interface MethodInfo {    /**     * 在自定义注解时,有以下几点需要我们了解:     * 1. 注解类型是通过"@interface"关键字定义的;     * 2. 在"注解体"中,所有的方法均没有方法体且只允许public和abstract这两种     *      修饰符号(不加修饰符缺省为public),注解方法不允许有throws子句;     * 3. 注解方法的返回值只能为以下几种:原始数据类型), String, Class, 枚举类型,     *       注解和它们的一维数组,可以为方法指定默认返回值。     */            String author() default "mazaiting";    String date();    int version() default 1;}
public class Client {        public static void main(String[] args) {        exec();        exec1();    }    @MethodInfo(date = "2017.8.29" )    private static void exec() {        System.out.println("exec");    }        @MethodInfo(author = "zaitingma",date = "2017.8.29",version=2)    private static void exec1() {        System.out.println("exec1");    }}

此时的注解还未曾起任何作用,接下来进行注解解析,解析后,注解就会起相应的作用。

  1. 注解的解析--编译时解析/运行时解析

编译时解析
编译时注解指的是@Retention的值为CLASS的注解,对于这类注解的解析,我们只需做以下两件事:
自定义类继承 AbstractProcessor类;
重写其中的 process 函数。
编译器在编译时会自动查找所有继承自 AbstractProcessor 的类,然后调用他们的 process 方法。

1. 新建注解类@Target({ ElementType.FIELD, ElementType.TYPE })  @Retention(RetentionPolicy.CLASS)  public @interface Seriable {        } 2. 新建BeanProcessor继承自AbstractProcessor类,类上必须加上注解@SupportedAnnotationTypes,括号中的字符串为新注解的包名+类名。@SupportedAnnotationTypes("com.mazaiting.Seriable")@SupportedSourceVersion(SourceVersion.RELEASE_8)public class BeanProcessor extends AbstractProcessor {    @Override    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {        try {            File file = new File("F:\\test.txt");            FileOutputStream fos = new FileOutputStream(file);            fos.write("wohenhao".getBytes());            fos.close();        } catch (Exception e) {            e.printStackTrace();        }        return true;    }}3. 导出为jar包右键工程->export->JAR file->finish.4. 新建测试工程将上一步导出的jar包引入新工程,新建主类public class Client {    @Seriable    String cString;    public static void main(String[] args) {        System.out.println(1);    }}5. 开启Factory Path右键工程->Java Compiler->Annotation Processing->Factory Path->Add JARs,选择刚刚导入的jar包,点击OK。6. 右键运行项目,在F盘下即可看到test.txt文件。

运行时解析

1. 新建注解@Documented@Target(ElementType.METHOD)@Inherited@Retention(RetentionPolicy.RUNTIME)public @interface AuthorAnno {    String name();    String website() default "mazaiting";    int version() default 1;}2. 创建主类,主类中public class AuthorAnnoDemo {    @AuthorAnno(name="mazaiting",website="zaitingma@foxmail.com",version=1)    public static void main(String[] args) throws SecurityException, ClassNotFoundException {        // 使用反射来解析注解        Parse.parse(AuthorAnnoDemo.class);        System.out.println("main");    }        @AuthorAnno(name = "zaitingma")    public void demo() {        System.out.println("demo");    }}3. 编写Parse.parse(Class<AuthorAnnoDemo> clazz) 方法来解析注解public class Parse {    public static void parse(Class<AuthorAnnoDemo> clazz) throws SecurityException, ClassNotFoundException {        // 获取类中的所有方法        Method[] methods = clazz.getMethods();              // 遍历方法        for (Method method : methods){            // 如果该方法的注解父类是AuthorAnno            if (method.isAnnotationPresent(AuthorAnno.class)) {                // 获取注解                AuthorAnno authorInfo = method.getAnnotation(AuthorAnno.class);                // 打印注解信息                System.out.println("method: "+ method);                System.out.println("name= "+ authorInfo.name() +                        " , website= "+ authorInfo.website()                       + " , revision= "+authorInfo.version());            }        }           }}

代码下载

原创粉丝点击