JAVA注解详解
刚接触项目,会在类上、函数、属性、参数等见识到各种各样的注解,认识这些注解的作用是了解项目结构,掌握项目业务逻辑的必备技能。
注解的概念:Java提供了一种原程序中的元素关联任何信息和任何元数据的途径和方法
要清晰概念首先要了解注解的本质其实就是接口,下面我们自定义个注解
public @interface MyAnnotation {
// 定义公共的final静态属性
int age = 25;
// 定义公共的抽象方法
String name();
}
反编译
java.lang.annotation.Annotation 本身是接口,而不是注解,当使用关键字@interface 定义一个注解时,该注解隐含的继承了java.lang.annotation.Annotation接口;如果我们定义一个接口,并且让该接口继承自Annotation,那么我们定义的接口依然是接口而不是注解。综上,定义注解只能依靠@interface实现
什么是原数据?
元数据是指用来描述数据的数据,更通俗一点,就是描述代码间关系,或者代码与其他资源(例如数据库表)之间内在联系的数据。
***接下来进入主题
注解按照来源分三类
1.JDK自带注解
@Oververride //方法重写
@Deprecated //提示作用,表示此方法已过时,过时的原因就是有新的API的类替代了此方法
@SuppressWarnings //阻止编译器发出某些警告信息
@SuppressWarnings
通过源码分析可知@SuppressWarnings其注解目标为类、字段、函数、函数入参、构造函数和函数的局部变量。建议把注解放在最近进警告发生的位置。
- @SuppressWarnings(“unchecked”) [ 抑制单类型的警告]
- @SuppressWarnings(“unchecked”,“rawtypes”) [ 抑制多类型的警告]
- @SuppressWarnings(“all”) [ 抑制所有类型的警告]
2.常见第三方注解
Spring: @Autowired @Service @Resipository
Mybatis: @InsertProvider @UpdateProvider @Options
第三方注解详解篇幅过长,客官网上另查哈~
3.自定义注解
既然元数据是指用来描述数据的数据,那么元注解就是注解的注解(在注解中再添加一层注解)
JAVA元注解有四种:
@Retention @Target @Document @Inherited;
@Target({ElementType.METHOD,ElementType.TYPE}) //注解的作用目标:函数,类
@Retention(RetentionPolicy.RUNTIME) //注解的保留位置:运行时存在
@Inherited //说明子类可以继承父类中的该注解
@Documented //说明该注解将被包含在javadoc中
public @interface Description {
String value();
int age() default 18;//设置默认值为18
}
注意:如果注解只有一个成员,成员名必须为value()
@Retention
@Retention(RetentionPolicy.SOURCE) //注解仅存在于源码中,在class字节码文件中不包含
@Retention(RetentionPolicy.CLASS) // 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得,
@Retention(RetentionPolicy.RUNTIME) // 注解会在class字节码文件中存在,在运行时可以通过反射获取到
@Target
@Target(ElementType.TYPE) //接口、类、枚举、注解
@Target(ElementType.FIELD) //字段、枚举的常量
@Target(ElementType.METHOD) //方法
@Target(ElementType.PARAMETER) //方法参数
@Target(ElementType.CONSTRUCTOR) //构造函数
@Target(ElementType.LOCAL_VARIABLE)//局部变量
@Target(ElementType.ANNOTATION_TYPE)//注解
@Target(ElementType.PACKAGE) ///包
实例:
去掉age属性留一个、
注解类
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Description {
String value();
}
接口类
public interface Cup {
public String name();
@Deprecated
public void function();
}
实体类
@Description("这是保温杯")
public class VacuumCup implements Cup {
public String name() {
return null;
}
@Description("这是保温功能")
public void function() {
}
测试(利用反射解析注解)
public class Test1 {
public static void main(String[] args){
Class clazz= null;
try {
clazz = Class.forName("com.rq.Cup.VacuumCup");
//找到类上的注解
if (clazz.isAnnotationPresent(Description.class)){
Description desc= (Description) clazz.getAnnotation(Description.class);
System.out.println(desc.value());
}
//找到方法上的注解
Method[] methods = clazz.getMethods();
for (Method method : methods) {
for (Annotation annotation : method.getAnnotations()) {
if (annotation instanceof Description) {
System.out.println(((Description) annotation).value());
}
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
输出: