语法:
@Target({ElementType.FIELD}) //作用目标
ElementType.CONSTRUCTOR 构造方法声明
ElementType.FIELD 字段声明
ElementType.LOCAL_VARIABLE 局部变量申明
ElementType.METHOD 方法声明
ElementType.PACKAGE 包声明
ElementType.PARAMETER 参数声明
ElementType.TYPE 类接口
@Retention(RetentionPolicy.RUNTIME) //保留
RetentionPolicy.SOURCE 只在源码显示,编译时会丢弃
RetentionPolicy.CLASS 编译时会记录到class中,运行时忽
RetentionPolicy.RUNTIME 运行时存在,可以通过发射读取
@Inherited //允许子类继承,可以不加
@Documented //注解应该被 javadoc工具记录,可以不加
以下为创建方法声明,实际中具体操作,和在被使用的过程,使用过程具体见日志管理有详细例子https://blog.csdn.net/qq_14840239/article/details/88863577
@Target(ElementType.METHOD) //方法生命
@Retention(RetentionPolicy.RUNTIME)
public @interface ILog {
String value() default "";
}
//--------------------------------------------------------
//使用
@ILog(value="获取数据")
//或 @ILog("获取数据")
public String getData(String id){
//代码
return data;
}
//--------------------------------------------------
//注释操作,
1.
//获得该对象,clazz是 Class<?>类
Object obj = clazz.getConstructor(new Class[]{}).newInstance(new Object[]{});
//变量该对象的方法
for (Method method : clazz.getDeclaredMethods()) {
//获取方法的注解,这里特定获取方法上@HelloWorld注解
ILog say = method.getAnnotation(ILog .class);
}
2.
//传入ProceedingJoinPoint joinPoint
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
ILog syslog = method.getAnnotation(ILog .class);