Annotation
概念:注解
原理
是一种接口,通过反射机制中的相关API来访问annotation信息
常见的标准Annotation
@Override 方法重写
@Deprecated 表示过期的东西警告
@SuppressWarnnings 取消显示指定的警告
自定义Annotation
访问修饰符 @interface Annotation名称{ 返回类型 method() [default 默认值]; ....... }
package com.tanlei.URL; public class MyAnnotation { @MyAnnotation1 public MyAnnotation() { } @MyAnnotation2(color=Color.RED) //@MyAnnotation2(value= {"zhangsa","lisi"}) // @MyAnnotation2(value = "tanlei" ,age=18) public static void main(String[] args) { @MyAnnotation1 int num=10; } } enum Color{ RED,BLUE,YELLOW; } //标记注解 @interface MyAnnotation1{ } //标记注解 @interface MyAnnotation2{ //String value() default "李四"; //int age(); //String [] value(); Color color(); }
Meta Annotation
元注解:
元注解的作用就是负责注解其他注解。Java5.0定义了4个标准的meta-annotation类型,它们被用来提供对其它 annotation类型作说明。Java5.0定义的元注解:
1.@Target,
2.@Retention,
3.@Documented,
4.@Inherited
这些类型和它们所支持的类在java.lang.annotation包中可以找到。下面我们看一下每个元注解的作用和相应分参数的使用说明。
@Target:
作用:用于描述注解的使用范围(即:被描述的注解可以用在什么地方)
取值(ElementType)有:
1.CONSTRUCTOR:用于描述构造器
2.FIELD:用于描述域
3.LOCAL_VARIABLE:用于描述局部变量
4.METHOD:用于描述方法
5.PACKAGE:用于描述包
6.PARAMETER:用于描述参数
7.TYPE:用于描述类、接口(包括注解类型) 或enum声明
@Target(ElementType.TYPE) public @interface Table { /** * 数据表名称注解,默认值为类名称 * @return */ public String tableName() default "className"; } @Target(ElementType.FIELD) public @interface NoDBColumn { }