java aop 获取参数名_SpringAOP中,获取参数名称

由于项目中打印日志的需要,研究了一下在aop中,获取参数名称的方法。

1、jdk1,8中,比较简单,直接通过joinPoint中的getSignature()方法即可获取

Signature signature = joinpoint.getSignature();

MethodSignature methodSignature = (MethodSignature) signature;

String[] strings = methodSignature.getParameterNames();

System.out.println(Arrays.toString(strings));

f8362479f3a6d3cd6f477aeb5d2b041c.png

2.通用方法。比较麻烦

public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable{

String classType = joinPoint.getTarget().getClass().getName();

Class> clazz = Class.forName(classType);

String clazzName = clazz.getName();

String methodName = joinPoint.getSignature().getName(); //获取方法名称

Object[] args = joinPoint.getArgs();//参数

//获取参数名称和值

Map nameAndArgs = getFieldsName(this.getClass(), clazzName, methodName,args);

System.out.println(nameAndArgs.toString());

//为了省事,其他代码就不写了,

return result = joinPoint.proceed();

}

private Map getFieldsName(Class cls, String clazzName, String methodName, Object[] args) throws NotFoundException {

Map map=new HashMap();

ClassPool pool = ClassPool.getDefault();

//ClassClassPath classPath = new ClassClassPath(this.getClass());

ClassClassPath classPath = new ClassClassPath(cls);

pool.insertClassPath(classPath);

CtClass cc = pool.get(clazzName);

CtMethod cm = cc.getDeclaredMethod(methodName);

MethodInfo methodInfo = cm.getMethodInfo();

CodeAttribute codeAttribute = methodInfo.getCodeAttribute();

LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);

if (attr == null) {

// exception

}

// String[] paramNames = new String[cm.getParameterTypes().length];

int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;

for (int i = 0; i < cm.getParameterTypes().length; i++){

map.put( attr.variableName(i + pos),args[i]);//paramNames即参数名

}

//Map<>

return map;

}

本文由【waitig】发表在等英博客 本文固定链接:SpringAOP中,获取参数名称 欢迎关注本站官方公众号,每日都有干货分享!

点赞 (1)赏分享 (0)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值