Java Annotation

http://www.javashuo.com/article/p-sroqmnzv-ko.htmljava

 

Annotation就是给代码打的标签,工具

 

元Annotation,定义Annotation自己的一些属性,经常使用的如下几种,spa

Retention注解.net

Retention(保留)注解说明,这种类型的注解会被保留到那个阶段. 有三个值:
1.RetentionPolicy.SOURCE —— 这种类型的Annotations只在源代码级别保留,编译时就会被忽略
2.RetentionPolicy.CLASS —— 这种类型的Annotations编译时被保留,在class文件中存在,但JVM将会忽略
3.RetentionPolicy.RUNTIME —— 这种类型的Annotations将被JVM保留,因此他们能在运行时被JVM或其余使用反射机制的代码所读取和使用.code

 

Documented 注解对象

Documented 注解代表这个注解应该被 javadoc工具记录. blog

 

Target注解token

@Target说明了Annotation所修饰的对象范围:接口

1.CONSTRUCTOR:用于描述构造器
2.FIELD:用于描述域
3.LOCAL_VARIABLE:用于描述局部变量
4.METHOD:用于描述方法
5.PACKAGE:用于描述包
6.PARAMETER:用于描述参数
7.TYPE:用于描述类、接口(包括注解类型) 或enum声明get

 

为何要有注解?

注解是介于代码和注释之间的存在,

用于将代码中的对象,进行分类或标识,这样在编译或运行时,能够作对不一样的分类作不一样的处理

 

如何使用?

注解经过 @interface关键字进行定义

public @interface TestAnnotation { }

 

注解只有成员变量,没有方法。注解的成员变量在注解的定义中以“无形参的方法”形式来声明

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
  public int id() default -1;
  public String msg() default "Hi";

}

 

使用的时候,

@TestAnnotation(id=3,msg="hello annotation") public class Test { }

或者,用默认值

@TestAnnotation() public class Test { }

 

若是是runtime的Annotation,

能够在代码里面这样获取,

boolean hasAnnotation = Test.class.isAnnotationPresent(TestAnnotation.class);

if ( hasAnnotation ) {
  TestAnnotation testAnnotation = Test.class.getAnnotation(TestAnnotation.class);

System.out.println("id:"+testAnnotation.id());
System.out.println("msg:"+testAnnotation.msg());

 

经常使用注释

@SuppressWarnings,抑制告警

@SuppressWarnings("unchecked"),强制类型转换时的告警

@SuppressWarnings("deprecation")

相关文章
相关标签/搜索