天天看點

自定義注解-java步驟:

步驟:

(1)@Target({ElementType.TYPE,ElementType.METHOD})表示可以修飾在類上、接口上、枚舉上、方法上

(2)@Retention(RetentionPolicy.RUNTIME)表示可以修飾在方法上

(3)使用反射來擷取接口、方法上的注解的執行個體

(4)可以結合spring的攔截器使用

public class Main {
    public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
        SystemConfig annotation = Test.class.getAnnotation(SystemConfig.class);
        print(annotation);
        Method[] methods = Test.class.getMethods();
        for(Method method:methods){
            SystemConfig annotation1 = method.getAnnotation(SystemConfig.class);
            if(annotation1!=null){
                print(annotation1);
            }
        }
    }
    private static void print(SystemConfig annotation){
        System.out.println(annotation.age()+","+annotation.name()+","+annotation.list()[0]+","+annotation.list()[1]);
    }
}
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface  SystemConfig{
    String name() default "lucy";
    int age ();
    int[] list() default {1,2};
}
@SystemConfig(name = "sum", age = 1,list = {3,4})
class Test{
    @SystemConfig(name = "sub", age = 2,list = {5,6})
    public void Test(){

    }
}