1 package org.slf4j.instrumentation;
2
3 import javassist.CtBehavior;
4 import javassist.CtClass;
5 import javassist.CtMethod;
6 import javassist.Modifier;
7 import javassist.NotFoundException;
8 import javassist.bytecode.AttributeInfo;
9 import javassist.bytecode.CodeAttribute;
10 import javassist.bytecode.LocalVariableAttribute;
11
12
13
14
15
16 public class JavassistHelper {
17
18
19
20
21
22
23
24
25
26
27
28 public static String returnValue(CtBehavior method) throws NotFoundException {
29
30 String returnValue = "";
31 if (methodReturnsValue(method)) {
32 returnValue = " returns: \" + $_ + \".";
33 }
34 return returnValue;
35 }
36
37
38
39
40
41
42
43
44
45 private static boolean methodReturnsValue(CtBehavior method)
46 throws NotFoundException {
47
48 if (method instanceof CtMethod == false) {
49 return false;
50 }
51
52 CtClass returnType = ((CtMethod) method).getReturnType();
53 String returnTypeName = returnType.getName();
54
55 boolean isVoidMethod = "void".equals(returnTypeName);
56
57 boolean methodReturnsValue = isVoidMethod == false;
58 return methodReturnsValue;
59 }
60
61
62
63
64
65
66
67
68
69
70 public static String getSignature(CtBehavior method) throws NotFoundException {
71
72 CtClass parameterTypes[] = method.getParameterTypes();
73
74 CodeAttribute codeAttribute = method.getMethodInfo().getCodeAttribute();
75
76 LocalVariableAttribute locals = null;
77
78 if (codeAttribute != null) {
79 AttributeInfo attribute;
80 attribute = codeAttribute.getAttribute("LocalVariableTable");
81 locals = (LocalVariableAttribute) attribute;
82 }
83
84 String methodName = method.getName();
85
86 StringBuffer sb = new StringBuffer(methodName + "(\" ");
87 for (int i = 0; i < parameterTypes.length; i++) {
88 if (i > 0) {
89
90 sb.append(" + \", \" ");
91 }
92
93 CtClass parameterType = parameterTypes[i];
94 boolean isArray = parameterType.isArray();
95 CtClass arrayType = parameterType.getComponentType();
96 if (isArray) {
97 while (arrayType.isArray()) {
98 arrayType = arrayType.getComponentType();
99 }
100 }
101
102 sb.append(" + \"");
103 sb.append(parameterNameFor(method, locals, i));
104 sb.append("\" + \"=");
105
106
107 if (isArray && !arrayType.isPrimitive()) {
108 sb.append("\"+ java.util.Arrays.asList($" + (i + 1) + ")");
109 } else {
110 sb.append("\"+ $" + (i + 1));
111 }
112 }
113 sb.append("+\")");
114
115 String signature = sb.toString();
116 return signature;
117 }
118
119
120
121
122
123
124
125
126
127
128
129 static String parameterNameFor(CtBehavior method,
130 LocalVariableAttribute locals, int i) {
131
132 if (locals == null) {
133 return Integer.toString(i + 1);
134 }
135
136 int modifiers = method.getModifiers();
137
138 int j = i;
139
140 if (Modifier.isSynchronized(modifiers)) {
141
142 j++;
143
144 }
145 if (Modifier.isStatic(modifiers) == false) {
146
147 j++;
148
149 }
150 String variableName = locals.variableName(j);
151
152
153
154
155
156 return variableName;
157 }
158 }