是附加在代码中的一些信息,可以认为是代码的一个标记,主要完成说明、配置的功能。我们平时用的注释是给人看的,而注解是给机器看的。
为了编程更简洁,使用注解,可以省去很多配置文件或者是代码;例如,对某个类的某种标记,如果没有注解,意味着可能要通过方法或者是配置文件来完成。
java注解的语法
import java.lang.annotation.*; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited public @interface UseCases { public int value() default 0; public int id() default 0; public String description() default "no description"; }
@UseCases(id=10, description="my desccription")
获取注解方法:
获取注解:注意: 要想使用反射去读取注解,必须将Retention的值选为Runtime
主要依靠java的反射机制来实现:
获取类的注解
Person.class.getAnnotation(annotationClass)
获取方法的注解
Person.class.getMethods()[0].getAnnotations()
获取字段的注解
obj.getClass().getDeclaredFields()[0].getAnnotations()
获取参数的注解
obj.getClass().getMethods()[0].getParameterAnnotations()
以上后四个是四种元注解,下面是三种内置标准
@Override 确保覆盖超类方法
@Deprecated 此方法过期,警告此用途
@SuppressWarnings 关闭不当警告