1 5 package org.exoplatform.text.template; 6 7 import java.lang.reflect.Method ; 8 import java.util.* ; 9 14 public class ReflectionBeanDataHandler implements DataHandler { 15 private static Object [] EMPTY_ARGS = {} ; 16 private static Map cache_ = new HashMap(300) ; 17 18 private Object bean_ ; 19 private Map methodMap_ ; 20 private Class type_ ; 21 22 public ReflectionBeanDataHandler(Class beanType) { 23 type_ = beanType ; 24 methodMap_ = getMethodMap(beanType) ; 25 } 26 27 public ReflectionBeanDataHandler(Object bean) { 28 bean_ = bean ; 29 type_ = bean.getClass() ; 30 methodMap_ = getMethodMap(type_) ; 31 } 32 33 public Class getDataTypeHandler() { return type_ ; } 34 35 public String getValueAsString(DataBindingValue value) { 36 try { 37 Method method = (Method )methodMap_.get(value.getMethodName()) ; 38 Object o = method.invoke(bean_, EMPTY_ARGS) ; 39 if(o == null) return "" ; 40 return o.toString(); 41 } catch (Exception ex) { 42 return value.getExpression() + " has error: " + ex.getMessage(); 43 } 44 } 45 46 public Object getValue(DataBindingValue value) { 47 try { 48 Method method = (Method )methodMap_.get(value.getMethodName()) ; 49 return method.invoke(bean_, EMPTY_ARGS) ; 50 } catch (Exception ex) { 51 return value.getExpression() + " has error: " + ex.getMessage(); 52 } 53 } 54 55 public void setBean(Object bean) { 56 bean_ = bean ; 57 } 58 59 private Map getMethodMap(Class type) { 60 Map methodMap = (Map)cache_.get(type) ; 61 if(methodMap == null) { 62 synchronized(cache_) { 63 Method [] methods = type.getMethods() ; 64 methodMap = new HashMap() ; 65 for(int i = 0 ; i < methods.length; i++) { 66 if(methods[i].getParameterTypes().length == 0) { 67 methodMap.put(methods[i].getName(), methods[i]) ; 68 } 69 } 70 cache_.put(type, methodMap) ; 71 } 72 } 73 return methodMap ; 74 } 75 } 76 | Popular Tags |