1. 定义Annotation
package com.thinking.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD, ElementType.CONSTRUCTOR})
@Retention(RetentionPolicy.RUNTIME)
public @interface Since {
String version() default "";
String author() default "";
}
@Target是为了限定此Annotation能够使用的范围,具体见java.lang.annotation.Target;
@Retention是为了限定Annotation存在的范围,具体见java.lang.annotation.Retention;
2. 使用Annotation
package com.thinking.annotation;
public class Person {
private String name = null;
@Since(version = "1.0")
public Person() {
}
@Since(version = "2.0", author = "meiping")
public String getName() {
return name;
}
}
3.解析Annotation
package com.thinking.annotation;
import java.lang.reflect.Method;
public class Thinking {
public static void main(String[] args) throws Exception {
Method method = Person.class.getMethod("getName");
if (method.isAnnotationPresent(Since.class)) {
Since annotation = method.getAnnotation(Since.class);
System.out.println(annotation.version());
System.out.println(annotation.author());
}
}
}