1 28 29 package com.idaremedia.antx.helpers; 30 31 import java.lang.reflect.Constructor ; 32 import java.util.Hashtable ; 33 34 import org.apache.tools.ant.BuildException; 35 36 48 49 public final class InstanceFactory extends Hashtable 50 { 51 52 public static final Class [] CTOR_SIG0= new Class [] {GenericParameters.class}; 53 54 55 56 59 public InstanceFactory() 60 { 61 } 62 63 64 65 70 public InstanceFactory(Class defaultClass) 71 { 72 setDefaultInstanceClass(defaultClass); 73 } 74 75 76 77 78 83 public void setDefaultInstanceClass(Class c) 84 { 85 if (c==null) { 86 throw new IllegalArgumentException (); 87 } 88 m_defaultClass = c; 89 } 90 91 92 93 97 public Class getDefaultInstanceClass() 98 { 99 return m_defaultClass; 100 } 101 102 103 104 110 public Object put(Object key, Object value) 111 { 112 if (value==null) { 113 return super.remove(key); 114 } 115 if (!(value instanceof Class )) { 116 throw new IllegalArgumentException ("Only class references allowed!"); 117 } 118 return super.put(key,value); 119 } 120 121 122 123 private Class getc(Object key) 124 { 125 Object rc = get(key); 126 Class c; 127 if (rc==null) { 128 c = getDefaultInstanceClass(); 129 } else { 130 c = (Class )rc; 131 } 132 return c; 133 } 134 135 136 137 143 public Object newInstance(Object key) 144 { 145 Class c = getc(key); 146 try { 147 return c.newInstance(); 148 } catch(Exception anyX) { 149 throw new BuildException(anyX); 150 } 151 } 152 153 154 155 162 public Object newInstance(Object key, GenericParameters args) 163 { 164 Class c = getc(key); 165 try { 166 Constructor ctor = c.getConstructor(CTOR_SIG0); 167 Object [] initargs = new Object [] {args}; 168 return ctor.newInstance(initargs); 169 } catch(Exception anyX) { 170 throw new BuildException(anyX); 171 } 172 } 173 174 175 private Class m_defaultClass = Object .class; 176 } 177 178 179 | Popular Tags |