深入理解java中的Annotation(注解)

来源:互联网 发布:mac 系统占用空间过大 编辑:程序博客网 时间:2024/06/06 07:20

一.介绍annotation

JDK1.5开始增加了Annotation功能,用于类,构造方法,成员变量,方法,参数等的声明中。该功能不会影响程序的运行,但是会对编译器警告等辅助功能产生影响,它能够工作的方式被看作类似程序的工具或者类库,它会反过来对正在进行的程序语义有所影响。annotation可以从源文件、class文件或者在运行时反射的多种方式被读取。
一个正式的Annotation功能:(1)允许开发者定义、使用自己的annotation类型(2)此功能由一个定义annotation类型的语法和一个描述annotation声明的语法,读取annotation的API,一个使用annotation修饰的class文件,一个annotation处理工具(apt)组成。

二.Java注解(Annotation)
Override 注解表示子类要重写(override)父类的对应方法。

public class OverrideTest {    @Override    //表示接下来的方法需要是重写父类的方法,否则报错,例如tostring会报错    public String toString(){        return "Thie is OverrideTest";    }    public static void main(String[] args){        OverrideTest test = new OverrideTest();        System.out.println(test);     }}

Deprecated注解表示方法是不建议被使用的。

//import java.util.Date;public class DeprecatedTest {    @Deprecated    public void doSomething(){        System.out.println("dosomething");    }    public static void main(String[] args){        DeprecatedTest test = new DeprecatedTest();        test.doSomething();//横线表示不建议被使用//      Date date = new Date();//      System.out.println(date.toLocaleString());//deprecated    }}

SuppressWarnings注解表示抑制警告。

import java.util.Date;import java.util.Map;import java.util.TreeMap;public class SuppressWaringsTest {    @SuppressWarnings("unchecked")//将调用集合的方法的警告压制住    public static void main(String[] args){        Map map = new TreeMap();         map.put("hello", new Date());        System.out.println(map.get("hello"));    }}

三.自定义重点内容注解

这里写图片描述

自定义注解:当注解中的属性名为value时,在对其赋值时可以不指定属性的名字而直接写上属性值即可;除了value以外的其他值都需要使用name = value这种赋值方式,即明确指定给谁赋值。

public @interface AnnotationTest {    String value();}public class AnnotationUsage {    @AnnotationTest ("hello") //直接赋值    public void method(){        System.out.println("usage of annotation");    }    public static void main(String[] args){        AnnotationUsage usage = new AnnotationUsage();        usage.method();    }}
public @interface AnnotationTest {    String name();}public class AnnotationUsage {    @AnnotationTest (name = "hello") //需要指定属性名字    public void method(){        System.out.println("usage of annotation");    }    public static void main(String[] args){        AnnotationUsage usage = new AnnotationUsage();        usage.method();    }}

也可以通过属性后加default的方式为成员设置默认值。

1 0