1 20 package org.enhydra.barracuda.plankton; 21 22 import java.io.*; 23 import java.util.*; 24 25 import org.apache.log4j.*; 26 27 30 public class Classes { 31 32 protected static final Logger logger = Logger.getLogger(Classes.class.getName()); 33 34 protected static Map clCache = null; 35 protected static final String NULL_STR = "~Null~"; 36 47 public synchronized static Class getClass(String clName) { 48 if (clName==null) return null; 49 if (clCache==null) clCache = new HashMap(); 50 Class cl = null; 51 try { 52 Object o = clCache.get(clName); 53 if (NULL_STR.equals(o)) { 54 logger.error("Error getting instance of class name:"+clName); 55 return null; 56 } 57 if (o!=null) { 58 cl = (Class ) o; 59 if (logger.isInfoEnabled()) logger.info("got cl from cache - name:"+clName+" class:"+cl); 60 } else { 61 cl = Class.forName(clName, true, Thread.currentThread().getContextClassLoader()); 62 clCache.put(clName, cl); 63 if (logger.isInfoEnabled()) logger.info("got cl from Class.forName() - name:"+clName+" class:"+cl); 64 } 65 } catch (Exception e) { 66 logger.error("Error creating Class reference for class name:"+clName+", err:"+e, e); 67 clCache.put(clName, NULL_STR); 68 cl = null; 69 } 70 return cl; 71 } 72 73 82 public static Object newInstance(Class cl) { 83 if (cl==null) return null; 84 try { 85 return cl.newInstance(); 86 } catch (Exception e) { 87 logger.error("Error instantiating class:"+cl+", err:"+e, e); 88 return null; 89 } 90 } 91 92 100 public static Object newInstance(String clName) { 101 return newInstance(getClass(clName)); 102 } 103 104 105 109 public static List getAllInterfaces(Object obj) { 110 List list = new ArrayList(); 111 return new Classes().getAllInterfaces(obj.getClass(), list); 112 } 113 114 public static List getAllInterfaces(Class cl) { 115 List list = new ArrayList(); 116 list.add(cl); 117 return new Classes().getAllInterfaces(cl, list); 118 } 119 120 private List getAllInterfaces(Class cl, List list) { 121 Class [] classes = cl.getInterfaces(); 122 for (int i=0; i<classes.length; i++) { 123 if (!list.contains(classes[i])) { 124 list.add(classes[i]); 125 getAllInterfaces(classes[i], list); 126 } 127 } 128 129 Class supercl = cl.getSuperclass(); 131 if (supercl!=null) getAllInterfaces(supercl, list); 132 134 return list; 135 } 136 137 140 public static String getShortClassName(Class cl) { 141 String className = cl.getName(); 142 int spos = className.lastIndexOf("."); 143 if (spos<0) return className; 144 else return className.substring(spos+1); 145 } 146 } | Popular Tags |