Spring AOP 利用 JoinPoint获得目标方法及其注解遇到的【java.lang.NoSuchMethodException】异常...

public class StudentImpl {

public void say(String msg) {

System.out.println("Say:" + msg);
}
public void run(Shoes shoes) {

System.out.println(shoes.getColour());
System.out.println(shoes.getMade());
System.out.println(shoes.getSpeed());
}
}
  /**
     * 方法开始执行
     */
    @Before("@annotation(autoLog)")
    public void doBefore(JoinPoint point,AutoLog autoLog) {

       try {
            Class clazz = joinPoint.getTarget().getClass();
            String targetName = clazz.getSimpleName();
            String methodName = joinPoint.getSignature().getName();
            Method methdo = clazz.getMethod(methodName);
            if (methdo.getAnnotation(AutoLog.class) != null) {
                System.out.println("not null");
            } else {
                System.out.println("null");
            }
        } catch (Exception ex) {
            System.out.println( ex.toString());
        }
    }
Method methdo = clazz.getMethod(methodName);这段程序执行报异常:java.lang.NoSuchMethodException

很多网上给的答案都是clazz.getMethod()和clazz.getDeclaredMethod()的区别(前者获得公共方法,后者所有方法),但是问题依旧,经过查资料发现,如果想获得该方法clazz.getMethod()有两个参数,第一参数代表要获得方法名称,第二个参数是方法执行需要的形参类型,代码修改成如下

try {
            Class clazz = joinPoint.getTarget().getClass();
            String targetName = clazz.getSimpleName();
            String methodName = joinPoint.getSignature().getName();
            Method methdo = clazz.getMethod(methodName,String.class);
            if (methdo.getAnnotation(AutoLog.class) != null) {
                System.out.println("not null");
            } else {
                System.out.println("null");
            }
        } catch (Exception ex) {
            System.out.println( ex.toString());
        }
Method methdo = clazz.getMethod(methodName,String.class); 正确写法
但是在实际应用过程中,通过aop反射想获得方法要动态获得方法形参,所以完整代码如下:
try {
    Class clazz = joinPoint.getTarget().getClass();

    String targetName = clazz.getSimpleName();
    String methodName = joinPoint.getSignature().getName();
    Class[] parameterTypes = ((MethodSignature)joinPoint.getSignature()).getMethod().getParameterTypes();
    Method methdo = clazz.getMethod(methodName,parameterTypes);
    if (methdo.getAnnotation(AutoLog.class) != null) {
        System.out.println("not null");
    } else {
        System.out.println("null");
    }
} catch (Exception ex) {
    ex.toString();
}

 这样就可以获得该方法并获得该方法的注解.谢谢

转载于:https://www.cnblogs.com/ff111/p/8707217.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值