AOP獲取引數名稱
阿新 • • 發佈:2019-01-27
由於專案中列印日誌的需要,研究了一下在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 > 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;
- }