您的位置:首页 > 编程语言 > Java开发

SpringAOP中,获取参数名称

2017-04-02 13:07 471 查看
由于项目中打印日志的需要,研究了一下在aop中,获取参数名称的方法。

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

Signature signature = joinpoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
String[] strings = methodSignature.getParameterNames();
System.out.println(Arrays.toString(strings));



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<String,Object > nameAndArgs = getFieldsName(this.getClass(), clazzName, methodName,args);
System.out.println(nameAndArgs.toString());
//为了省事,其他代码就不写了,
return result = joinPoint.proceed();

}
private Map<String,Object> getFieldsName(Class cls, String clazzName, String methodName, Object[] args) throws NotFoundException {
Map<String,Object > map=new HashMap<String,Object>();

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: