1 20 package org.enhydra.barracuda.contrib.dbroggisch.display; 21 22 import java.util.*; 23 import java.lang.reflect.*; 24 import org.apache.log4j.*; 25 26 public class ReflectionMapper { 27 private static Logger logger = Logger.getLogger(ReflectionMapper.class.getName()); 28 static Map s_getters = new HashMap(); 29 30 private static class Getter { 31 public Method method; 32 public String name; 33 } 34 35 private static void createGetters(Class obj) { 36 try { 37 List getters = new ArrayList(); 38 if(logger.isDebugEnabled()) { 39 logger.debug("Class " + obj); 40 } 41 Method [] ms = obj.getMethods(); 42 for(int i = 1; i < ms.length; i++) { 43 String name = ms[i].getName(); 44 if(logger.isDebugEnabled()) { 45 logger.debug("processing method " + name); 46 } 47 if(name.startsWith("get")) { 48 Getter g = new Getter(); 49 g.method = ms[i]; 50 g.name = name.substring(3).toUpperCase(); 51 getters.add(g); 52 if(logger.isDebugEnabled()) { 53 logger.debug("Added Getter with name " + g.name); 54 } 55 } 56 } 57 s_getters.put(obj, getters); 58 } catch(SecurityException ex) { 59 } 60 } 61 62 private static synchronized List getGetters(Class klass) { 63 if(!s_getters.containsKey(klass)) { 64 createGetters(klass); 65 } 66 return (List)s_getters.get(klass); 67 } 68 69 public static List map(List objs) { 70 ArrayList res = new ArrayList(objs.size()); 71 for(Iterator it = objs.iterator(); it.hasNext();) { 72 res.add(map(it.next())); 73 } 74 return res; 75 } 76 77 public static LightweightTemplateModel map(Object obj) { 78 return map(new HashMapModel(), obj); 79 } 80 81 public static LightweightTemplateModel map(LightweightTemplateModel model, Object obj) { 82 if(obj == null || model == null) 83 return model; 84 85 List getters = getGetters(obj.getClass()); 86 87 88 for(Iterator it = getters.iterator(); it.hasNext();) { 89 try { 90 Getter g = (Getter)it.next(); 91 Object value = g.method.invoke(obj, null); 92 if(logger.isDebugEnabled()) { 93 logger.debug("Value: " + value); 94 } 95 model.setItem(g.name, value); 96 } catch(IllegalAccessException ex) { 97 ex.printStackTrace(); 98 } catch(InvocationTargetException ex) { 99 ex.printStackTrace(); 100 } 101 } 102 return model; 103 } 104 } 105 | Popular Tags |