1、概述
Java提供了一种原程序中的元素关联任何信息和任何元数据的途径和方法
2、Java中的常见注解
JDK自带注解
Java第三方注解
JDK自带注解
@Overrider
表示重写(当然不写也可以),不过写上有如下好处: 1、可以当注释用,方便阅读; 2、编译器可以给你验证@Override下面的方法名是否是你父类中所有的,如果没有则报错。例如,你如果没写@Override,而你下面的方法名又写错了,这时你的编译器是可以编译通过的,因为编译器以为这个方法是你的子类中自己增加的方法。
@Deprecated
表示修饰的方法已过时,这个方法或类不再建议使用。在新版本中有其他方法或类可以代替这个使用,以后的版本也不会再更新这个方法或类。
@Suppvisewarnings
压制警告,用于通知java编译器禁止特定的编译警告
常见第三方注解
@Autowired
是一种函数,可以对成员变量、方法和构造函数进行标注,来完成自动装配的工作。
@Resource
作用相当于@Autowired,只不过@Autowired按byType自动注入,而@Resource默认按
byName自动注入罢了。
@Service
用于标注业务层组件
@Controller/RestController
用于标注控制层组件
@Repository
用于标注数据访问组件,即DAO组件。
@Component
泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。
3、Java注解的分类
按照运行机制分
源码注解
注解只在源码中存在,编译成.class文件就不存在了。
编译时注解
注解在源码和.class文件中都存在,比如Java自带的注解@Overrider、@Deprecated等。
运行时注解
在运行阶段还起作用,甚至会影响运行逻辑的注解,比如spring的@Autowired注解等。
按照来源分
来自JDK的注解
来自第三方的注解
我们自定义的注解
元注解
还有一类叫元注解,给注解进行注解的注解叫做元注解。
首先注解这个东西它们都有继承一个叫做Annotation的接口,类似于Class中的Object一样!
元注解有以下4种:
@Target 代表注解的使用范围
@Retention 代表注解的生命周期
@Documented 文档生成
@Inherited 允许子类继承父类中的注解
4、自定义注解
自定义注解的语法要求
使用自定义注解
5、解析注解
通过反射函数获取类、函数或成员上的运行时注解信息,从而实现动态控制程序运行的逻辑。看下面源码:
首先,创建名为Description的注解
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Description {
String desc();
String author();
int age() default 18;
}
创建一个Child类,在它的类和方法上使用@Description注解
@Description(desc = "I am class annotation", author = "child")
public class Child {
@Description(desc = "I am method annotation", author = "name()")
public String name() {
return null;
}
}
然后,我们就开始解析注解
public class AnnotationTest{
public static void main(String[] args) {
try {
//1.使用类加载器加载类
Class c = Class.forName("com.momo.study.annotation.Child");
//2.找到类上面的注解
boolean isExist = c.isAnnotationPresent(Description.class);
if(isExist) {
//3.拿到注解实例
Description description = (Description)c.getAnnotation(Description.class);
System.out.println("Description: " + description.desc());
}
//4.找到方法上的注解
Method[] methods = c.getMethods();
for(Method method : methods) {
boolean isMExist = method.isAnnotationPresent(Description.class);
if(isMExist) {
Description description = (Description)method.getAnnotation(Description.class);
System.out.println("Description: " + description.desc());
}
}
//另一种解析方法
for(Method method : methods) {
Annotation[] annotations = method.getAnnotations();
for(Annotation annotation : annotations) {
if(annotation instanceof Description) {
System.out.println("Description: " + ((Description) annotation).desc());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("欢迎来到注解世界...");
}
}
编译执行程序,我们就能在程序执行中RUNTIME通过反射函数获取类、函数或成员上的运行时注解信息
Description: I am class annotation
Description: I am method annotation
Description: I am method annotation
欢迎来到注解世界...
进程完成,退出码 0