通过注解实现面向切片编程的核心步骤
定义注解
声明的方式
- 对于JavaType.java文件,我们常用的是用来声明类(class)或接口(interface)
| 12
 
 | public class JavaType{}
 
 | 
或者
| 12
 
 | public interface JavaType{}
 
 | 
这里我们使用@interface来定义一个annnotation注解
| 12
 
 | public @interface JavaType{}
 
 | 
在@interface上使用注解
@Target注解
- 用来声明注解的使用目标,常见@Target的值有:ElementType.Method用于方法,ElementType.Type用于类型(包括java类、接口、注解), ElementType.Parameter用于方法参数,还有更多枚举可以从ElementType中找到具体定义
| 12
 
 | @Target(ElementType.METHOD)public interface JavaType{}
 
 | 
@Retention注解
- 使用有道词典翻译是保持力的名词意思,此注解的@Target声明的是ANNOTATION_TYPE,用于为注解类型提供声明
- @Retention配置的值从RetentionPolicy.java枚举中选择,可选值为SOURCE,CLASS,RUNTIME
- SOURCE定义的注解保留在源代码中,不编译到Class中去,如@Override和@SuppressWarnings注解使用本策略
- CLASS定义的注解会保留到class文件,但是运行期间不会识别此注解
- RUNTIME定义的注解会被保留到class文件中,同时运行期间也会被识别,AOP中使用的注解一般情况下使用本策略
@Documented
- 用于javadoc的一个注解,声明注解时使用了本注解时,在到处javadoc时,在javadoc中就能看到目标的注解声明
在一个注解中定义方法
| 12
 3
 4
 5
 6
 7
 8
 
 | import java.lang.annotation.*;
 @Target(ElementType.METHOD)
 @Retention(RetentionPolicy.RUNTIME)
 @Documented
 public @interface JavaType {
 String value() default "";
 }
 
 | 
| 12
 3
 4
 
 | public class Test{@JavaType("value")
 public void typeA(){}
 }
 
 | 
- 关键字default指定默认值,默认值必须是与元素的数据类型兼容的类型
- 定义二: 使用枚举
| 12
 3
 4
 5
 6
 7
 8
 
 | import java.lang.annotation.*;
 @Target(ElementType.METHOD)
 @Retention(RetentionPolicy.RUNTIME)
 @Documented
 public @interface JavaType {
 RetentionPolicy value() default RetentionPolicy.RUNTIME;
 }
 
 | 
| 12
 3
 4
 5
 6
 7
 
 | import java.lang.annotation.RetentionPolicy;
 public class Test {
 @JavaType(RetentionPolicy.CLASS)
 public void typeA() {
 }
 }
 
 | 
| 12
 3
 4
 5
 6
 7
 8
 
 | import java.lang.annotation.*;
 @Target(ElementType.ANNOTATION_TYPE)
 @Retention(RetentionPolicy.RUNTIME)
 @Documented
 public @interface Target {
 ElementType[] value();
 }
 
 | 
| 12
 3
 4
 5
 6
 
 | import java.lang.annotation.ElementType;import java.lang.annotation.Target;
 
 @Target({ElementType.METHOD, ElementType.TYPE})
 public @interface JavaType {
 }
 
 |