现有注解如下:
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注解
应该怎么做?
@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);
}
}
}
}
}
我又修改了下调用的方法
public class Demo1 {
public static void main(String[] args) {
Method[] methods = Test.class.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.getDeclaredAnnotationsByType(NoNull.class);
for (int k = 0; k < annotations.length; k++) {
Annotation annotation = annotations[k];
System.out.println(annotation);
}
}
}
}
}