/**
* 1,注解
*
* 注解是java 的一个新的类型(与接口很相似),它与类/接口/枚举是在同一个层次,它们都称作为java 的一个类型(TYPE).它可以声明在包/类/字段/方法/局部变量/方法参数等的前面,用来对这些元素进行说明,注释.
* 作用包括:进行编译检查/生成说明文档/跟踪代码依赖性,实现替代配置文件功能。等.
*
* 1.1,JDK的lang包提供的几个基本注解
*
* @Override 表示当前方法是覆盖父类的方法。
@Deprecated 表示当前元素是反对使用(往往是过时)的。
@SuppressWarnings表示关闭一些不当的编译器警告信息。
*
* 1.2,元注解:注解的注解
* 元注解@Target,@Retention,@Documented,@Inherited
*
* @Target 表示该注解用于什么地方,可能的 ElemenetType 参数包括:
* ElemenetType.CONSTRUCTOR 构造器声明
* ElemenetType.FIELD 域声明(包括 enum 实例)
* ElemenetType.LOCAL_VARIABLE 局部变量声明
* ElemenetType.METHOD 方法声明
* ElemenetType.PACKAGE 包声明
* ElemenetType.PARAMETER 参数声明
* ElemenetType.TYPE 类,接口(包括注解类型)或enum声明
*
* @Retention 表示在什么级别保存该注解信息。可选的 RetentionPolicy 参数包括:
* RetentionPolicy.SOURCE 注解将被编译器丢弃
* RetentionPolicy.CLASS 注解在class文件中可用,但会被VM丢弃
* RetentionPolicy.RUNTIME VM将在运行期也保留注释,因此可以通过反射机制读取注解的信息。
*
* @Documented 将此注解包含在 javadoc 中
*
* @Inherited 允许子类继承父类中的注解
*/
//1.3,注解的定义
import java.lang.annotation.Retention;
@Retention(RetentionPolicy.RUNTIME)//枚举三种阶段:CLASS运行期不读取/RUNTIME运行时读取/SOURCE编译时标记
@Target({ElementType.METHOD,ElementType.TYPE})//枚举标记到哪个成分:方法/类
public @interface ItcastAnnotation {
public int id();
public String description() default "hello";
// String[] color3() default {"blue","red"};
}
//1.4,注解的使用和反射
import java.lang.reflect.Method;
@IAnnotation(id=0)
public class AnnotationTest {
/*
* 被注解的三个方法
*/
@IAnnotation(id= 1, description = "method_1")
public void method_1() {
}
@IAnnotation(id= 2)
public void method_2() {
}
@IAnnotation(id= 3, description = "method_3")
public void method_3() {
}
public static void main(String[] args) {
Method[] methods = AnnotationTest.class.getDeclaredMethods();
for(Method method : methods) {
// 判断方法中是否有指定注解类型的注解
boolean hasAnnotation = method.isAnnotationPresent(IAnnotation.class);
if(hasAnnotation) {
//根据注解类型返回方法中的指定类型注解
IAnnotation annotation = method.getAnnotation(IAnnotation.class);
System.out.println("Test(method = " + method.getName()+" , id = " + annotation.id() + " , description = "+annotation.description() + " )");
}
}
// 可以直接判断和反射获得注解类的类上注解@IAnnotation(id=0)
if(AnnotationTest.class.isAnnotationPresent(IAnnotation.class))
{ IAnnotation annotation = (IAnnotation)AnnotationTest.class.getAnnotation(IAnnotation.class);
System.out.println(annotation);
}
}
}