1 19 package jcckit.util; 20 21 import java.lang.reflect.*; 22 23 29 public class Factory { 30 31 public static final String CLASS_NAME_KEY = "className"; 32 33 34 private Factory() {} 35 36 43 public static Object create(String className) { 44 try { 45 return Class.forName(className).newInstance(); 46 } catch (Throwable t) { 47 throw new IllegalArgumentException ("Could not create an instance of " 48 + className + " because of " + t); 49 } 50 } 51 52 67 public static Object create(ConfigParameters configParameters) { 68 String className = configParameters.get(CLASS_NAME_KEY); 69 return createObject(configParameters, className); 70 } 71 72 83 public static Object create(ConfigParameters configParameters, 84 String defaultClassName) { 85 String className = configParameters.get(CLASS_NAME_KEY, defaultClassName); 86 return createObject(configParameters, className); 87 } 88 89 96 public static Object createOrGet(ConfigParameters configParameters, 97 Object defaultObject) { 98 String className = configParameters.get(CLASS_NAME_KEY, null); 99 return className == null ? defaultObject 100 : createObject(configParameters, className); 101 } 102 103 private static Object createObject(ConfigParameters configParameters, 104 String className) { 105 try { 106 Class c = Class.forName(className); 107 Object result = null; 108 Constructor constructor = null; 109 try { 110 constructor = c.getConstructor(new Class [] {ConfigParameters.class}); 111 result = constructor.newInstance(new Object [] {configParameters}); 112 } catch (NoSuchMethodException e) { 113 result = c.newInstance(); 114 } 115 return result; 116 } catch (Throwable t) { 117 throw new FactoryException(configParameters, CLASS_NAME_KEY, t); 118 } 119 } 120 } 121 | Popular Tags |