adinlead 2017-05-22 10:53 采纳率: 0%
浏览 7442

Java中,如何在外部获取方法参数的注解值?

现有注解如下:

 package anno;

/**
 * Created by adinlead on 17-5-22.
 */
public @interface NoNull {
    boolean fields() default true;
}

方法如下:

package controllers;

import anno.NoNull;

/**
 * Created by adinlead on 17-5-22.
 */
public class Test {
    public static void test(@NoNull String str) {
        if (str == null){
            System.out.println("拦截失败");
        }
        System.out.println("拦截成功");
    }
}

在框架调用test之前,我可以手动写个方法来检查
我想在检查中获取test方法的参数是否带有@NoNull注解
应该怎么做?

  • 写回答

2条回答 默认 最新

  • CSDNRGY 2017-05-23 06:47
    关注
     @Target(ElementType.PARAMETER)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface NoNull {
        boolean fields() default true;
    }
    
     public class Test {
        public static void test(@NoNull String str) {
            if (str == null){
                System.out.println("拦截失败");
            }
            System.out.println("拦截成功");
        }
    }
    
    public class Demo1 {
    
        public static void main(String[] args) {
            f1(Test.class);
        }
    
        private static <T> void f1(Class<T> cls) {
            Method[] methods = cls.getDeclaredMethods();
            for (int i = 0; i < methods.length; i++) {
                Method method = methods[i];
                method.setAccessible(true);
                Parameter[] parameters = method.getParameters();
                for (int j = 0; j < parameters.length; j++) {
                    Parameter parameter = parameters[j];
                    Annotation[] annotations = parameter.getDeclaredAnnotations();
                    for (int k = 0; k < annotations.length; k++) {
                        Annotation annotation = annotations[k];
                        System.out.println(annotation);
                    }
                }
            }
        }
    } 
    
    评论

报告相同问题?