一、自定义注解须知
元注解的作用就是负责注解其他注解。Java5.0定义了4个标准的meta-annotation类型,它们被用来提供对其它 annotation类型作说明。
Java5.0定义的元注解:
1.@Target,
2.@Retention,
3.@Documented,
4.@Inherited
作用:用于描述注解的使用范围(即:被描述的注解可以用在什么地方)
取值(ElementType)有:
1.CONSTRUCTOR:用于描述构造器
2.FIELD:用于描述域
3.LOCAL_VARIABLE:用于描述局部变量
4.METHOD:用于描述方法
5.PACKAGE:用于描述包
6.PARAMETER:用于描述参数
7.TYPE:用于描述类、接口(包括注解类型) 或enum声明
作用:表示需要在什么级别保存该注释信息,用于描述注解的生命周期(即:被描述的注解在什么范围内有效)
取值(RetentionPoicy)有:
1.SOURCE:在源文件中有效(即源文件保留)
2.CLASS:在class文件中有效(即class保留)
3.RUNTIME:在运行时有效(即运行时保留)
二、使用aop实现注解进行日志打印
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLog {
/**
* 描述
* @return {String}
*/
String value();
}
@Slf4j
@Aspect
@AllArgsConstructor
public class SysLogAspect {
@SneakyThrows
@Around("@annotation(sysLog)")
public Object around(ProceedingJoinPoint point, SysLog sysLog) {
String strClassName = point.getTarget().getClass().getName();
String strMethodName = point.getSignature().getName();
log.debug("[类名]:{},[方法]:{}", strClassName, strMethodName);
//注解值
sysLog.value();
Long startTime = System.currentTimeMillis();
Object obj = point.proceed();
Long endTime = System.currentTimeMillis();
return obj;
}
}
//提一嘴HttpServletRequest懂的都懂 request 都来了做点日志记录 ip 等等
HttpServletRequest request = ((ServletRequestAttributes) Objects
.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
三、反射使用注解
@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD})
@Documented
public @interface MyAnnotation {
String name();
int age() default 18;
int[] score();
}
public class Student{
//记得加注解测试
// @MyAnnotation(....)
public void study(int times){
for(int i = 0; i < times; i++){
System.out.println("Good Good Study, Day Day Up!");
}
}
}
public static void main(String[] args) {
try{
//获取Student的Class对象
Class stuClass = Class.forName("com.hong.example.Student");
//这里的形参不能写成Integer.class,应该写int.class //参数类型.class
Method stuMethod = stuClass.getMethod("study",int.class);
if (stuMethod.isAnnotationPresent(MyAnnotation.class)){
System.out.println("Student类上配置了MyAnnotation注解!");
//获取该元素上指定类型的注解
MyAnnotation myAnnotation = stuMethod.getAnnotation(MyAnnotation.class);
System.out.print("name: "+myAnnotation.name()+", age: "+myAnnotation.age()+", score:");
for (int i = 0 ;i < myAnnotation.score().length;i++){
System.out.print(myAnnotation.score()[i]+" ");
}
}else{
System.out.println("Student类上没有配置MyAnnotation注解");
}
System.out.println();
}catch (ClassNotFoundException | NoSuchMethodException e){
e.printStackTrace();
}
}