目前我有一个@Select注解,如下
@SqlCommand
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Select {
String[] value() default {};
}
我想要在intercept的时候获取这个注解的类和他的value,应该这样做
package com.autumn.proxy;
import com.autumn.anno.sql.Select;
import com.autumn.anno.sql.SqlCommand;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
public class MapperProxy implements MethodInterceptor {
@Override
public Object intercept(Object target, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
Annotation[] annotations = method.getAnnotations();
Annotation sqlAnno = null;
for (Annotation annotation : annotations) {
if (annotation.annotationType().isAnnotationPresent(SqlCommand.class)) {
sqlAnno = annotation;
break;
}
}
if (sqlAnno == null) {
throw new RuntimeException("Method name of " + method.getName() + " is not defined in interface " + target.getClass().getName());
}
System.out.println(sqlAnno.getClass());
//获取注解的真实类
Class annoClass = sqlAnno.annotationType();
System.out.println(annoClass);
//获取value属性
System.out.println(annoClass.getDeclaredMethod("value"));
String[] sqls = (String[]) annoClass.getDeclaredMethod("value").invoke(sqlAnno);
System.out.println(Arrays.toString(sqls));
System.out.println("参数:" + Arrays.toString(args));
return null;
}
}
输出: