1 28 package net.sf.jasperreports.engine.util; 29 30 import net.sf.jasperreports.engine.JRException; 31 32 import org.apache.commons.collections.ReferenceMap; 33 34 35 41 public class JRSingletonCache 42 { 43 private final ReferenceMap cache; 44 private final Class itf; 45 46 51 public JRSingletonCache(Class itf) 52 { 53 cache = new ReferenceMap(); 54 this.itf = itf; 55 } 56 57 68 public synchronized Object getCachedInstance(String className) throws JRException 69 { 70 Object instance = cache.get(className); 71 if (instance == null) 72 { 73 try 74 { 75 Class clazz = JRClassLoader.loadClassForName(className); 76 if (itf != null && !itf.isAssignableFrom(clazz)) 77 { 78 throw new JRException("Class \"" + className + "\" should be compatible with \"" + itf.getName() + "\""); 79 } 80 81 instance = clazz.newInstance(); 82 } 83 catch (ClassNotFoundException e) 84 { 85 throw new JRException("Class " + className + " not found.", e); 86 } 87 catch (InstantiationException e) 88 { 89 throw new JRException("Error instantiating class " + className + ".", e); 90 } 91 catch (IllegalAccessException e) 92 { 93 throw new JRException("Error instantiating class " + className + ".", e); 94 } 95 96 cache.put(className, instance); 97 } 98 return instance; 99 } 100 } 101 | Popular Tags |