1 16 package org.apache.commons.collections.functors; 17 18 import java.io.Serializable ; 19 import java.lang.reflect.InvocationTargetException ; 20 import java.lang.reflect.Method ; 21 22 import org.apache.commons.collections.FunctorException; 23 import org.apache.commons.collections.Transformer; 24 25 33 public class InvokerTransformer implements Transformer, Serializable { 34 35 36 static final long serialVersionUID = -8653385846894047688L; 37 38 39 private final String iMethodName; 40 41 private final Class [] iParamTypes; 42 43 private final Object [] iArgs; 44 45 52 public static Transformer getInstance(String methodName) { 53 if (methodName == null) { 54 throw new IllegalArgumentException ("The method to invoke must not be null"); 55 } 56 return new InvokerTransformer(methodName); 57 } 58 59 67 public static Transformer getInstance(String methodName, Class [] paramTypes, Object [] args) { 68 if (methodName == null) { 69 throw new IllegalArgumentException ("The method to invoke must not be null"); 70 } 71 if (((paramTypes == null) && (args != null)) 72 || ((paramTypes != null) && (args == null)) 73 || ((paramTypes != null) && (args != null) && (paramTypes.length != args.length))) { 74 throw new IllegalArgumentException ("The parameter types must match the arguments"); 75 } 76 if (paramTypes == null || paramTypes.length == 0) { 77 return new InvokerTransformer(methodName); 78 } else { 79 paramTypes = (Class []) paramTypes.clone(); 80 args = (Object []) args.clone(); 81 return new InvokerTransformer(methodName, paramTypes, args); 82 } 83 } 84 85 90 private InvokerTransformer(String methodName) { 91 super(); 92 iMethodName = methodName; 93 iParamTypes = null; 94 iArgs = null; 95 } 96 97 105 public InvokerTransformer(String methodName, Class [] paramTypes, Object [] args) { 106 super(); 107 iMethodName = methodName; 108 iParamTypes = paramTypes; 109 iArgs = args; 110 } 111 112 118 public Object transform(Object input) { 119 if (input == null) { 120 return null; 121 } 122 try { 123 Class cls = input.getClass(); 124 Method method = cls.getMethod(iMethodName, iParamTypes); 125 return method.invoke(input, iArgs); 126 127 } catch (NoSuchMethodException ex) { 128 throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" + input.getClass() + "' does not exist"); 129 } catch (IllegalAccessException ex) { 130 throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" + input.getClass() + "' cannot be accessed"); 131 } catch (InvocationTargetException ex) { 132 throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" + input.getClass() + "' threw an exception", ex); 133 } 134 } 135 136 } 137 | Popular Tags |