注解学习

自定义注解

方法参数的注解

@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD, ElementType.PARAMETER})
public @interface Parama {
    String value() default "";

    String name() default "";

}

方法的注解

@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = {ElementType.TYPE, ElementType.METHOD})
public @interface MyAnnotation {
    String color() default "white";
}

注解获取解析


@MyAnnotation(color = "yellow")
public class Main {

    public static void main(String[] args) {
        System.out.println("Hello World!");
        if (Main.class.isAnnotationPresent(MyAnnotation.class)) {
            System.out.println("获取到runtime @ ");
        }
        Annotation[] subs = Main.class.getAnnotations();

        MyAnnotation myAnnotation = Main.class.getAnnotation(MyAnnotation.class);
        if (myAnnotation != null) {
            System.out.println(myAnnotation + " : " + myAnnotation.color());

        }
        Main main = new Main();
       main.sayHello("132","XXXX");
    }
@Parama(name = "name",value = "xxx")
    public  void sayHello(@Parama("hello") String msg, @Parama("xx") String xx) {

    for (Method method : this.getClass().getMethods()) {

        if(method.getAnnotation(Parama.class) == null ){
            continue;
        }
        Annotation[][] params = method.getParameterAnnotations();

        for (int i = 0; i < params.length; i++) {
            Annotation[] annotations = params[I];
            for (int j = 0; j < annotations.length; j++) {
                Annotation annotation = annotations[j];
                if (annotation instanceof Parama) {
                    Parama parama = (Parama) annotation;
                    String pValue = parama.value();
                    String pName = parama.name();

                    System.out.println("获取到funcation的参数注解:" + "值:"+ pValue +" : 参数名:"+pName);
                }
            }
        }
    }
    }
}

结果

http://springforall.ufile.ucloud.com.cn/static/img/7e9fd2d95ec8f790f9dca29ffdf6c3331559212

你可能感兴趣的:(注解学习)