美文网首页
注解学习

注解学习

作者: 搞好关系 | 来源:发表于2019-06-01 22:33 被阅读0次

    自定义注解

    方法参数的注解

    @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

    相关文章

      网友评论

          本文标题:注解学习

          本文链接:https://www.haomeiwen.com/subject/gzsztctx.html