1 16 package org.apache.commons.collections.functors; 17 18 import java.io.Serializable ; 19 import java.lang.reflect.Constructor ; 20 import java.lang.reflect.InvocationTargetException ; 21 22 import org.apache.commons.collections.FunctorException; 23 import org.apache.commons.collections.Transformer; 24 25 33 public class InstantiateTransformer implements Transformer, Serializable { 34 35 36 static final long serialVersionUID = 3786388740793356347L; 37 38 39 public static final Transformer NO_ARG_INSTANCE = new InstantiateTransformer(); 40 41 42 private final Class [] iParamTypes; 43 44 private final Object [] iArgs; 45 46 53 public static Transformer getInstance(Class [] paramTypes, Object [] args) { 54 if (((paramTypes == null) && (args != null)) 55 || ((paramTypes != null) && (args == null)) 56 || ((paramTypes != null) && (args != null) && (paramTypes.length != args.length))) { 57 throw new IllegalArgumentException ("Parameter types must match the arguments"); 58 } 59 60 if (paramTypes == null || paramTypes.length == 0) { 61 return NO_ARG_INSTANCE; 62 } else { 63 paramTypes = (Class []) paramTypes.clone(); 64 args = (Object []) args.clone(); 65 } 66 return new InstantiateTransformer(paramTypes, args); 67 } 68 69 72 private InstantiateTransformer() { 73 super(); 74 iParamTypes = null; 75 iArgs = null; 76 } 77 78 85 public InstantiateTransformer(Class [] paramTypes, Object [] args) { 86 super(); 87 iParamTypes = paramTypes; 88 iArgs = args; 89 } 90 91 97 public Object transform(Object input) { 98 try { 99 if (input instanceof Class == false) { 100 throw new FunctorException( 101 "InstantiateTransformer: Input object was not an instanceof Class, it was a " 102 + (input == null ? "null object" : input.getClass().getName())); 103 } 104 Constructor con = ((Class ) input).getConstructor(iParamTypes); 105 return con.newInstance(iArgs); 106 107 } catch (NoSuchMethodException ex) { 108 throw new FunctorException("InstantiateTransformer: The constructor must exist and be public "); 109 } catch (InstantiationException ex) { 110 throw new FunctorException("InstantiateTransformer: InstantiationException", ex); 111 } catch (IllegalAccessException ex) { 112 throw new FunctorException("InstantiateTransformer: Constructor must be public", ex); 113 } catch (InvocationTargetException ex) { 114 throw new FunctorException("InstantiateTransformer: Constructor threw an exception", ex); 115 } 116 } 117 118 } 119 | Popular Tags |