本例使用的自定义注解类
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD, ElementType.LOCAL_VARIABLE,
ElementType.PARAMETER,ElementType.TYPE,ElementType.FIELD,ElementType.CONSTRUCTOR})
@Retention(RetentionPolicy.RUNTIME)
public @interface Novel {
/**
* 有默认值的属性不用写,写了标灰
* 如果只有一个无默认值的value属性,且没有其他的无默认值的属性,那么value字段可以不用写
*/
boolean value() default true;
String name();
int century() default 19;
String[] character();
}
使用规则
//注解类,本例value有了默认值,可以不写
@Novel(value = true,name = "Don Quixote",character = {"Sancho","Panza"})
public class AnnotationDemo1 {
//注解成员变量,这里用一个静态的示例
@Novel(name = "LongNightOdyssey",century = 20,character = {"Louis","Ferdinand"})
public static String[] bookCart;
//注解方法,虽然是个main方法
@Novel(name = "Writing Degree Zero",century = 20,character = {"Roland","Barthes"})
public static void main(String[] args) {
//注解本地变量
@Novel(name = "Iliad", character = {"Hector","Agamemnon","Achilles"})
String critic;
purchase("SevenStars",99.9);
}
//注解构造器
@Novel(name = "Pale Fire",character = {"John","Shade"})
public AnnotationDemo1(){}
//注解方法里的参数
static void purchase(@Novel(name = "Tess",character = {"Tess"})String shop, double price){
System.out.println("You purchased it through "+shop+", and the price is "+ price);
}
}
用于解析注解的对象
@Novel(name = "One thousand and one nights",character = {"Ibrahim","Scheherazade"})
public class BookShelf {
@Novel(name = "Human comedy",character = {"Lucian","Carlos","Estell"})
public void stock(){
}
}
解析执行体
用到了Junit框架@Test,代替main方法执行
import org.junit.jupiter.api.Test;
import java.lang.reflect.Method;
import java.util.Arrays;
public class AnnotationDemo2 {
@Test
public void parseClass(){
Class<BookShelf> cl = BookShelf.class;
if (cl.isAnnotationPresent(Novel.class)){
/**
* 获得Class对象的时候如果不是这样写Class<BookShelf> cl = BookShelf.class;
* 那么获得注解类就应该这么写
* Annotation nv = cl.getDeclaredAnnotation(Novel.class);
* 因为注解类全是Annotation的实现类,为了拿到Novel类自身的属性,要做类型转换
* Novel nv = (Novel)cl.getDeclaredAnnotation(Novel.class);
* 一开始Class<BookShelf>之后,则无须类型转换的写法了
*/
Novel nv = cl.getDeclaredAnnotation(Novel.class);
System.out.println(nv.value());
System.out.println(nv.name());
System.out.println(nv.century());
System.out.println(Arrays.toString(nv.character()));
}
}
@Test
public void parseMethod() throws NoSuchMethodException {
Class<BookShelf> cl = BookShelf.class;
Method me = cl.getDeclaredMethod("stock");
if (me.isAnnotationPresent(Novel.class)){
Novel nv = me.getDeclaredAnnotation(Novel.class);
System.out.println(nv.value());
System.out.println(nv.name());
System.out.println(nv.century());
System.out.println(Arrays.toString(nv.character()));
}
}
}