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 StaticMethodInvoker {
30 private String methodName;
31 private Class<?>[] argTypes;
32 private Class<?> receiverType;
33 private Object[] args;
34
35 public StaticMethodInvoker(Class<?> receiverType, String methodName) {
36 this(receiverType, methodName, new Object[0]);
37 }
38
39 public StaticMethodInvoker(Class<?> receiverType, String methodName, Object arg) {
40 this(receiverType, methodName, new Object[]{arg});
41 }
42
43 public StaticMethodInvoker(Class<?> receiverType, String methodName, Object[] args) {
44 this.receiverType = receiverType;
45 this.methodName = methodName;
46 this.args = args;
47 argTypes = new Class[args.length];
48 for (int i = 0; i < args.length; i++) {
49 argTypes[i] = args[i].getClass();
50 }
51 }
52
53 public Method getMethod() throws NoSuchMethodException {
54 try {
55 return receiverType.getMethod(methodName, argTypes);
56 } catch (NoSuchMethodException e) {
57 convertToPrimitives();
58 try {
59 return receiverType.getMethod(methodName, argTypes);
60 } catch (NoSuchMethodException e1) {
61 String classes = "(";
62 for (int i = 0; i < argTypes.length; i++) {
63 Class<?> argType = argTypes[i];
64 classes += " " + argType.getName();
65 if (i != argTypes.length - 1) {
66 classes += ",";
67 }
68 }
69 classes += ")";
70 throw new NoSuchMethodException(methodName + classes);
71 }
72
73 }
74 }
75
76 private void convertToPrimitives() {
77 Class<?>[] newArgTypes = new Class[argTypes.length];
78 for (int i = 0; i < argTypes.length; i++) {
79 Class<?> argType = argTypes[i];
80 if (argType.equals(Boolean.class)) {
81 newArgTypes[i] = Boolean.TYPE;
82 } else if (argType.equals(Byte.class)) {
83 newArgTypes[i] = Byte.TYPE;
84 } else if (argType.equals(Character.class)) {
85 newArgTypes[i] = Character.TYPE;
86 } else if (argType.equals(Double.class)) {
87 newArgTypes[i] = Double.TYPE;
88 } else if (argType.equals(Float.class)) {
89 newArgTypes[i] = Float.TYPE;
90 } else if (argType.equals(Integer.class)) {
91 newArgTypes[i] = Integer.TYPE;
92 } else if (argType.equals(Long.class)) {
93 newArgTypes[i] = Long.TYPE;
94 } else if (argType.equals(Short.class)) {
95 newArgTypes[i] = Short.TYPE;
96 } else {
97 newArgTypes[i] = argType;
98 }
99 }
100 argTypes = newArgTypes;
101 }
102
103 public Object invoke() throws NoSuchMethodException, IllegalAccessException,
104 IllegalArgumentException, InvocationTargetException {
105 return getMethod().invoke(null, args);
106 }
107 }