1 15 package org.apache.hivemind.lib.impl; 16 17 import java.util.Collections ; 18 import java.util.HashMap ; 19 import java.util.Map ; 20 21 import org.apache.hivemind.ApplicationRuntimeException; 22 import org.apache.hivemind.impl.BaseLocatable; 23 import org.apache.hivemind.lib.DefaultImplementationBuilder; 24 import org.apache.hivemind.service.ClassFab; 25 import org.apache.hivemind.service.ClassFabUtils; 26 import org.apache.hivemind.service.ClassFactory; 27 import org.apache.hivemind.service.MethodIterator; 28 29 34 public class DefaultImplementationBuilderImpl extends BaseLocatable implements 35 DefaultImplementationBuilder 36 { 37 private Map _instances = Collections.synchronizedMap(new HashMap ()); 38 39 private ClassFactory _classFactory; 40 41 public Object buildDefaultImplementation(Class interfaceType) 42 { 43 Object result = _instances.get(interfaceType); 44 45 if (result == null) 46 { 47 result = create(interfaceType); 48 49 _instances.put(interfaceType, result); 50 } 51 52 return result; 53 } 54 55 private Object create(Class interfaceType) 56 { 57 Class defaultClass = createClass(interfaceType); 58 59 try 60 { 61 return defaultClass.newInstance(); 62 } 63 catch (Exception ex) 64 { 65 throw new ApplicationRuntimeException(ImplMessages.unableToCreateDefaultImplementation( 66 interfaceType, 67 ex), ex); 68 } 69 } 70 71 private Class createClass(Class interfaceType) 72 { 73 if (!interfaceType.isInterface()) 74 throw new ApplicationRuntimeException(ImplMessages.notAnInterface(interfaceType)); 75 76 String name = ClassFabUtils.generateClassName(interfaceType); 77 78 ClassFab cf = _classFactory.newClass(name, Object .class); 79 80 cf.addInterface(interfaceType); 81 82 MethodIterator mi = new MethodIterator(interfaceType); 83 84 while (mi.hasNext()) 85 { 86 ClassFabUtils.addNoOpMethod(cf, mi.next()); 87 } 88 89 if (!mi.getToString()) 90 ClassFabUtils.addToStringMethod(cf, ImplMessages 91 .defaultImplementationDescription(interfaceType)); 92 93 return cf.createClass(); 94 } 95 96 public void setClassFactory(ClassFactory factory) 97 { 98 _classFactory = factory; 99 } 100 101 } | Popular Tags |