1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package net.sourceforge.jwebunit.tests.util.reflect;
20
21 import java.lang.reflect.InvocationTargetException;
22 import java.lang.reflect.Method;
23
24
25
26
27
28
29 public class MethodInvoker {
30 private Object receiver;
31 private String methodName;
32 private Class<?>[] argTypes;
33 private Class<?> receiverType;
34 private Object[] args;
35
36 public MethodInvoker(Object receiver, String methodName) {
37 this(receiver, methodName, new Object[0]);
38 }
39
40 public MethodInvoker(Object receiver, String methodName, Object arg) {
41 this(receiver, methodName, new Object[]{arg});
42 }
43
44 public MethodInvoker(Object receiver, String methodName, Object[] args) {
45 this.receiver = receiver;
46 receiverType = receiver.getClass();
47 this.methodName = methodName;
48 this.args = args;
49 argTypes = new Class[args.length];
50 for (int i = 0; i < args.length; i++) {
51 argTypes[i] = args[i].getClass();
52 }
53 }
54
55 public Method getMethod() throws NoSuchMethodException {
56 try {
57 return receiverType.getMethod(methodName, argTypes);
58 } catch (NoSuchMethodException e) {
59 convertToPrimitives();
60 try {
61 return receiverType.getMethod(methodName, argTypes);
62 } catch (NoSuchMethodException e1) {
63 String classes = "(";
64 for (int i = 0; i < argTypes.length; i++) {
65 Class<?> argType = argTypes[i];
66 classes += " " + argType.getName();
67 if (i != argTypes.length - 1) {
68 classes += ",";
69 }
70 }
71 classes += ")";
72 throw new NoSuchMethodException(methodName + classes);
73 }
74
75 }
76 }
77
78 private void convertToPrimitives() {
79 Class<?>[] newArgTypes = new Class[argTypes.length];
80 for (int i = 0; i < argTypes.length; i++) {
81 Class<?> argType = argTypes[i];
82 if (argType.equals(Boolean.class)) {
83 newArgTypes[i] = Boolean.TYPE;
84 } else if (argType.equals(Byte.class)) {
85 newArgTypes[i] = Byte.TYPE;
86 } else if (argType.equals(Character.class)) {
87 newArgTypes[i] = Character.TYPE;
88 } else if (argType.equals(Double.class)) {
89 newArgTypes[i] = Double.TYPE;
90 } else if (argType.equals(Float.class)) {
91 newArgTypes[i] = Float.TYPE;
92 } else if (argType.equals(Integer.class)) {
93 newArgTypes[i] = Integer.TYPE;
94 } else if (argType.equals(Long.class)) {
95 newArgTypes[i] = Long.TYPE;
96 } else if (argType.equals(Short.class)) {
97 newArgTypes[i] = Short.TYPE;
98 } else {
99 newArgTypes[i] = argType;
100 }
101 }
102 argTypes = newArgTypes;
103 }
104
105 public Object invoke() throws NoSuchMethodException, IllegalAccessException,
106 IllegalArgumentException, InvocationTargetException {
107 return getMethod().invoke(receiver, args);
108 }
109 }