注解
定义:注解(Annotation),也叫元数据。一种代码级别的说明。它是JDK1.5及以后版本引入的一个特性,与类、接口、枚举是在同一个层次。它可以声明在包、类、字段、方法、局部变量、方法参数等的前面,用来对这些元素进行说明,注释。
使用方法
我们平时在进行Junit单元测试的时候,需要加上@Test
这个就是一种注解。此注解用于Junit识别测试方法。
自定义注解
注解的定义和类接口等一样不过其声明标识符为@interface
而且其遍历表示方法也不一样
//声明其注解作用范围
@Retention(RetentionPolicy.RUNTIME)
//声明可以注解的类型
@Target(value = {ElementType.TYPE,ElementType.METHOD})
public @interface HelloWorld {
//注解内的参数
String value();
}
@Retention中的参数有三种
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
}
参数名 | 作用 |
---|---|
SOURCE | SOURCE这个policy表示注解保留在源代码中,但是编译的时候会被编译器所丢弃 |
CLASS | CLASS和RUNTIME的唯一区别是RUNTIME在运行时期间注解是存在的,而CLASS则不存在。 |
RUNTIME | 大部分情况下,我们都是使用RUNTIME这个Policy。 |
@Target的参数有10种
public enum ElementType {
/** Class, interface (including annotation type), or enum declaration */
TYPE,
/** Field declaration (includes enum constants) */
FIELD,
/** Method declaration */
METHOD,
/** Formal parameter declaration */
PARAMETER,
/** Constructor declaration */
CONSTRUCTOR,
/** Local variable declaration */
LOCAL_VARIABLE,
/** Annotation type declaration */
ANNOTATION_TYPE,
/** Package declaration */
PACKAGE,
/**
* Type parameter declaration
*
* @since 1.8
*/
TYPE_PARAMETER,
/**
* Use of a type
*
* @since 1.8
*/
TYPE_USE
}
参数名 | 作用 |
---|---|
TYPE | 注解类、接口(包括注解类型)或枚举 |
FIELD | 注解字段(包括枚举常量) |
METHOD | 注解方法 |
PARAMETER | 注解参数 |
CONSTRUCTOR | 注解构造方法 |
LOCAL_VARIABLE | 注解局部变量 |
ANNOTATION_TYPE | 注解 注解 |
PACKAGE | 注解包 |
TYPE_PARAMETER | 用于类型参数,即泛型方法、泛型类、泛型接口 |
TYPE_USE | 类型使用.可以用于标注任意类型除了 class |
自定义注解的使用
1.先自己声明注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.TYPE,ElementType.METHOD})
public @interface HelloWorld {
String value();
}
2.使用
@HelloWorld(value = "HelloWorld")
public void test(){}
声明一个方法然后加上注解
3.获取注解的方法
Class<Main> mainClass = Main.class;
Method method = mainClass.getMethod("test");
HelloWorld annotation = method.getAnnotation(HelloWorld.class);
System.out.println(annotation.value());
先获取到方法然后通过方法的getAnnotation获取到注解,然后进行相应的操作