Java 注解Annotation

来源:互联网 发布:手机版数据库 编辑:程序博客网 时间:2024/06/06 06:45

1.JDK内置的基本注解类型(3个)

1)@Override:限定重写父类方法,该注解只能用于方法

2)@Deprecated:用于表示某个程序元素(类,方法等)已过时

3)@SuppressWarnings:抑制编译器警告

import java.util.ArrayList;import java.util.List;/** * 注解: * 1.JDK提供的常用的注解 * 2.自定义注解 * 3.元注解 */public class TestAnnotation {    public static void main(String[] args) {        Person p = new Student();        p.walk(); // Student walk        p.eat(); //过时也是可以调用的        @SuppressWarnings({"rawtypes", "unused"}) //抑制编译器警告        List list = new ArrayList();    }}@MyAnnotation(value = "world")class Student extends Person {    @Override    public void walk() {        System.out.println("Student walk");    }    @Override    public void eat() {        System.out.println("Student eat");    }}@Deprecatedclass Person {    String name;    int age;    public Person() {    }    public Person(String name, int age) {        super();        this.name = name;        this.age = age;    }    public void walk() {        System.out.println("walk");    }   @Deprecated    public void eat() {        System.out.println("eat");    }}

2.自定义注解

import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import static java.lang.annotation.ElementType.*;import static java.lang.annotation.ElementType.CONSTRUCTOR;import static java.lang.annotation.ElementType.LOCAL_VARIABLE;/** * 自定义的注解 */@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})@Retention(RetentionPolicy.CLASS)public @interface MyAnnotation {    String value() default "hello";}


3.元注解

JDK的元Annotation用于修饰其他Annotation定义

JDK5.0提供了专门在注解上的注释类型,分别是:

1)Retention

2)Target

3)Documented

4)Inherited


@Retention时必须为该value成员变量指定值:
1>RetentionPolicy.SOURCE:编译器直接丢弃这种策略的注释

2>RetentionPolicy.CLASS:编译器将把注释记录在class文件中。当运行Java程序时,JVM不会保留注释。这是默认值。

3>RetentionPolicy.RUNTIME:编译器将把注释记录在class文件中,当运行Java程序时,JVM会保留注释,程序可以通过反射获取该注释。

@Target

用来说明可以修饰哪些结构。

@Documented

形成文档时可以保留。

@Inherited

被修饰的对象将具有继承性。

原创粉丝点击