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