1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46 package org.codehaus.groovy.classgen;
47
48 import java.lang.reflect.Method;
49
50 import org.objectweb.asm.MethodVisitor;
51 import org.objectweb.asm.Opcodes;
52 import org.objectweb.asm.Type;
53
54 /***
55 * A helper class to invoke methods more easily in ASM
56 *
57 * @author <a href="mailto:james@coredevelopers.net">James Strachan</a>
58 * @version $Revision: 1.3 $
59 */
60 public class MethodCaller implements Opcodes {
61
62 private int opcode;
63 private String internalName;
64 private String name;
65 private Class theClass;
66 private String methodDescriptor;
67
68 public static MethodCaller newStatic(Class theClass, String name) {
69 return new MethodCaller(INVOKESTATIC, theClass, name);
70 }
71
72 public static MethodCaller newInterface(Class theClass, String name) {
73 return new MethodCaller(INVOKEINTERFACE, theClass, name);
74 }
75
76 public static MethodCaller newVirtual(Class theClass, String name) {
77 return new MethodCaller(INVOKEVIRTUAL, theClass, name);
78 }
79
80 public MethodCaller(int opcode, Class theClass, String name) {
81 this.opcode = opcode;
82 this.internalName = Type.getInternalName(theClass);
83 this.theClass = theClass;
84 this.name = name;
85
86 }
87
88 public void call(MethodVisitor methodVisitor) {
89 methodVisitor.visitMethodInsn(opcode, internalName, name, getMethodDescriptor());
90 }
91
92 public String getMethodDescriptor() {
93 if (methodDescriptor == null) {
94 Method method = getMethod();
95 methodDescriptor = Type.getMethodDescriptor(method);
96 }
97 return methodDescriptor;
98 }
99
100 protected Method getMethod() {
101 Method[] methods = theClass.getMethods();
102 for (int i = 0; i < methods.length; i++) {
103 Method method = methods[i];
104 if (method.getName().equals(name)) {
105 return method;
106 }
107 }
108 throw new ClassGeneratorException("Could not find method: " + name + " on class: " + theClass);
109 }
110 }