Java注解
定义
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
public int id() default -1;
public String msg() default "Hi";
}
元注解
- @Target(ElementType.TYPE) 标志该注解在什么地方
- @Retention(RetentionPolicy.RUNTIME) 标志注解的生效范围
- @Inherited 可继承,继承标记该注解的超类,子类也可以获得该注解
-
@Repeatable 与容器注解
@interface Persons { Person[] value(); } @Repeatable(Persons.class) @interface Person{ String role default ""; } @Person(role="artist") @Person(role="coder") @Person(role="PM") public class SuperMan{ }
通过反射使用
结合aop使用
- changelog的aop例子
@Aspect
public class ChangeLogAspect {
@Pointcut("execution(public * com.ximalaya..*.*(..))&&@annotation(com.ximalaya.platform.changelog.annotation.ChangeLog)")
public void changeLog() {
}
@Around("changeLog()")
public ChangInfo buildChangInfo(ProceedingJoinPoint joinPoint) {
//get method from JoinPoint
Method method = this.getAnnotationMethod(joinPoint);
//get annotation instance of method
ChangeLog annotation = (ChangeLog)method.getAnnotation(ChangeLog.class);
ChangeInfo changeInfo = new ChangeInfo();
changeInfo.setDescription(annotation.description());
changeInfo.setOperationType(annotation.operationType());
changeInfo.setOperationSource(annotation.operationSource());
return changInfo;
}
}