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.Factory; 23 import org.apache.commons.collections.FunctorException; 24 25 33 public class InstantiateFactory implements Factory, Serializable { 34 35 36 static final long serialVersionUID = -7732226881069447957L; 37 38 39 private final Class iClassToInstantiate; 40 41 private final Class [] iParamTypes; 42 43 private final Object [] iArgs; 44 45 private transient Constructor iConstructor = null; 46 47 55 public static Factory getInstance(Class classToInstantiate, Class [] paramTypes, Object [] args) { 56 if (classToInstantiate == null) { 57 throw new IllegalArgumentException ("Class to instantiate must not be null"); 58 } 59 if (((paramTypes == null) && (args != null)) 60 || ((paramTypes != null) && (args == null)) 61 || ((paramTypes != null) && (args != null) && (paramTypes.length != args.length))) { 62 throw new IllegalArgumentException ("Parameter types must match the arguments"); 63 } 64 65 if (paramTypes == null || paramTypes.length == 0) { 66 return new InstantiateFactory(classToInstantiate); 67 } else { 68 paramTypes = (Class []) paramTypes.clone(); 69 args = (Object []) args.clone(); 70 return new InstantiateFactory(classToInstantiate, paramTypes, args); 71 } 72 } 73 74 80 public InstantiateFactory(Class classToInstantiate) { 81 super(); 82 iClassToInstantiate = classToInstantiate; 83 iParamTypes = null; 84 iArgs = null; 85 findConstructor(); 86 } 87 88 96 public InstantiateFactory(Class classToInstantiate, Class [] paramTypes, Object [] args) { 97 super(); 98 iClassToInstantiate = classToInstantiate; 99 iParamTypes = paramTypes; 100 iArgs = args; 101 findConstructor(); 102 } 103 104 107 private void findConstructor() { 108 try { 109 iConstructor = iClassToInstantiate.getConstructor(iParamTypes); 110 111 } catch (NoSuchMethodException ex) { 112 throw new IllegalArgumentException ("InstantiateFactory: The constructor must exist and be public "); 113 } 114 } 115 116 121 public Object create() { 122 if (iConstructor == null) { 124 findConstructor(); 125 } 126 127 try { 128 return iConstructor.newInstance(iArgs); 129 130 } catch (InstantiationException ex) { 131 throw new FunctorException("InstantiateFactory: InstantiationException", ex); 132 } catch (IllegalAccessException ex) { 133 throw new FunctorException("InstantiateFactory: Constructor must be public", ex); 134 } catch (InvocationTargetException ex) { 135 throw new FunctorException("InstantiateFactory: Constructor threw an exception", ex); 136 } 137 } 138 139 } 140 | Popular Tags |