`

Annotation-java注解

    博客分类:
  • java
阅读更多

Java中提供3个内置注释类型

a. Override ,只能用于方法(不能用于类,包声明或者其他构造)
 作用:注释能实现编译时检查,你可以为你的方法添加该注释,以声明该方法是用于覆盖父类中的方法。如果该方法不是覆盖父类的方法,将会在编译时报错。 用法:
 @Override
  public void fun(){..}

b.Deprecated  同样只能作用与方法
 作用:是对不应该在使用的方法添加注释,当编程人员使用这些方法时,将会在编译时显示提示信息,它与javadoc里的@deprecated标记有相同的功能,准确的说,它还不如javadoc @deprecated,因为它不支持参数.

 用法:
 @Deprecated
 public void fun{...}

 

c.SupressWarnings 可以注释一段代码
 作用:关闭特定的警告信息,例如你在使用泛型的时候未指定类型
 用法: 

     与前两个注释有所不同,你需要添加一个参数才能正确使用,这些参数值都是已经定义好了的,我们选择性的使用就好了,参数如下: 

     deprecation   使用了过时的类或方法时的警告

     unchecked  执行了未检查的转换时的警告,例如当使用集合时没有用泛型 (Generics) 来指定集合保存的类型

     fallthrough   Switch 程序块直接通往下一种情况而没有 Break 时的警告

     path   在类路径、源文件路径等中有不存在的路径时的警告

     serial 当在可序列化的类上缺少 serialVersionUID 定义时的警告

     finally    任何 finally 子句不能正常完成时的警告

     all 关于以上所有情况的警告 


 @SupressWarnings(value={"unchecked"})
 public void fun{...}

 

 

 

Java中还提供了四种元注释,专门负责注释其他的注释

@Target表示该注释可以用于什么地方。
   可用的ElementType参数包括:
       CONSTRUCTOR : 构造器的声明
       FIELD : 域声明(包括enum实例)
       LOCAL_VARIABLE : 局部变量声明
       METHOD : 方法声明
       PACKAGE : 包声明
       PARAMETER : 参数声明
       TYPE : 类、接口 (包括注解类型) 或enum声明

public enum ElementType {
    /** Class, interface (including annotation type), or enum declaration */
    TYPE,

    /** Field declaration (includes enum constants) */
    FIELD,

    /** Method declaration */
    METHOD,

    /** Parameter declaration */
    PARAMETER,

    /** Constructor declaration */
    CONSTRUCTOR,

    /** Local variable declaration */
    LOCAL_VARIABLE,

    /** Annotation type declaration */
    ANNOTATION_TYPE,

    /** Package declaration */
    PACKAGE
}

  

@Retention 表示需要在什么级别保存该注释信息。可选的RetentionPoicy参数包括:
        SOURCE : 注释将被编译器丢掉
        CLASS : 注释在class文件中可用,但会被VM丢弃
        RUNTIME : VM将在运行时也保留注释,因此可以通过反射机制读取注释的信息。

public enum RetentionPolicy {
    /**
     * Annotations are to be discarded by the compiler.
     */
    SOURCE,

    /**
     * Annotations are to be recorded in the class file by the compiler
     * but need not be retained by the VM at run time.  This is the default
     * behavior.
     */
    CLASS,

    /**
     * Annotations are to be recorded in the class file by the compiler and
     * retained by the VM at run time, so they may be read reflectively.
     *
     * @see java.lang.reflect.AnnotatedElement
     */
    RUNTIME
}

 

@Documented 将注释包含在JavaDoc中

@Inheried  允许子类继承父类中的注释。

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics