通过反射获得更详细的参数信息

private static ClassPool pool = ClassPool.getDefault();

 public static void log(JoinPoint point) throws TException, NotFoundException {
  if (point != null) {
   StringBuilder sb = new StringBuilder();
   MethodSignature ms = (MethodSignature) point.getSignature();
   CtClass cc = pool.get(point.getTarget().getClass().getName());
   sb.append("类名:" + cc.getName());
   CtMethod cm = cc.getDeclaredMethod(ms.getName());
   sb.append(", 方法名:" + cm.getName());
   MethodInfo mi = cm.getMethodInfo();
   CodeAttribute ca = mi.getCodeAttribute();
   LocalVariableAttribute attr = (LocalVariableAttribute) ca
     .getAttribute(LocalVariableAttribute.tag);
   String[] params = new String[cm.getParameterTypes().length];
   int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
   int index = 0;
   for (int i = 0; i < params.length; i++) {
    index = i + pos;
    params[i] = attr.variableName(index);
    // System.out.println(attr.descriptor(index));
   }
   Object[] args = point.getArgs();
   if (params.length > 0) {
    sb.append(", 参数列表 [");
    for (int i = 0; i < params.length; i++) {
     if (i != 0)
      sb.append(",");
     sb.append(params[i] + ": " + args[i]);
    }
    sb.append("]");
   }
   System.out.println(sb.toString());
  }
 }

 

 

用AOP实现LOG的场合用

你可能感兴趣的:(反射)