An annotation is a form of metadata, that can be added to Java source code. Classes, methods, variables, parameters and packages may be annotated. Annotations have no direct effect on the operation of the code they annotate.
Annotations have a number of uses, among them:Information for the complier - Annotations can be used by the compiler to detect errors or suppress warnings.Compiler-time and deployment-time processing - Software tools can process annotation information to generate code, XML files, and so forth.Runtime processing - Some annotations are available to be examined at runtime.
元注解是专门修饰注解的注解。它们都是为了更好的设计自定义注解的细节而专门设计的。
@Target(ElementType.TYPE) :类、接口(包括注解类型)或enum声明。
@Target(ElementType.FIELD):字段、枚举的常量。
@Target(ElementType.METHOD):METHOD:方法声明。
@Target(ElementType.PARAMETER):方法参数声明。
@Target(ElementType.CONSTRUCTOR):构造器的声明。
@Target(ElementType.LOCAL_VARIABLE):局部变量声明。
@Target(ElementType.ANNOTATION_TYPE):注解类型声明。
@Target(ElementType.PACKAGE):包声明。
@Retention(RetentionPolicy.SOURCE):注解将被编译器丢弃。
@Retention(RetentionPolicy.CLASS):注解在class文件中可用,在jvm中丢弃。
@Retention(RetentionPolicy.RUNTIME):jvm在运行期也保留注解,可以通过反射机制来读取注解的信息。
/**
* 自定义注解
* 配置输出的信息
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD})
public @interface OutMessage {
String message() default "";
}
/**
* 切面类
*/
@Aspect
@Component
public class OutMessageAspect {
/**
* 定义切点
*/
@Pointcut("@annotation(cn.mejiwef.annotationdemo.selftest.OutMessage)")
public void messagePoint() {
}
@Around("messagePoint()")
public Object setMessage(ProceedingJoinPoint pjp) throws Throwable {
Signature signature = pjp.getSignature();
MethodSignature ms = (MethodSignature) signature;
OutMessage annotation = ms.getMethod().getAnnotation(OutMessage.class);
String message = annotation.message();
return pjp.proceed(new Object[]{message});
}
}
// 方法上使用自定义注解
@OutMessage(message = "hello world")
public void p(String message) {
System.out.println(message);
}
原文:https://www.cnblogs.com/vivfeng/p/11642533.html