KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > exoplatform > text > template > ReflectionBeanDataHandler


1 /***************************************************************************
2  * Copyright 2001-2003 The eXo Platform SARL All rights reserved. *
3  * Please look at license.txt in info directory for more license detail. *
4  **************************************************************************/

5 package org.exoplatform.text.template;
6
7 import java.lang.reflect.Method JavaDoc;
8 import java.util.* ;
9 /**
10  * @author Tuan Nguyen (tuan08@users.sourceforge.net)
11  * @since Feb 1, 2005
12  * @version $Id$
13  */

14 public class ReflectionBeanDataHandler implements DataHandler {
15   private static Object JavaDoc[] EMPTY_ARGS = {} ;
16   private static Map cache_ = new HashMap(300) ;
17   
18   private Object JavaDoc bean_ ;
19   private Map methodMap_ ;
20   private Class JavaDoc type_ ;
21   
22   public ReflectionBeanDataHandler(Class JavaDoc beanType) {
23     type_ = beanType ;
24     methodMap_ = getMethodMap(beanType) ;
25   }
26   
27   public ReflectionBeanDataHandler(Object JavaDoc bean) {
28     bean_ = bean ;
29     type_ = bean.getClass() ;
30     methodMap_ = getMethodMap(type_) ;
31   }
32   
33   public Class JavaDoc getDataTypeHandler() { return type_ ; }
34   
35   public String JavaDoc getValueAsString(DataBindingValue value) {
36     try {
37       Method JavaDoc method = (Method JavaDoc)methodMap_.get(value.getMethodName()) ;
38       Object JavaDoc o = method.invoke(bean_, EMPTY_ARGS) ;
39       if(o == null) return "" ;
40       return o.toString();
41     } catch (Exception JavaDoc ex) {
42       return value.getExpression() + " has error: " + ex.getMessage();
43     }
44   }
45   
46   public Object JavaDoc getValue(DataBindingValue value) {
47     try {
48       Method JavaDoc method = (Method JavaDoc)methodMap_.get(value.getMethodName()) ;
49       return method.invoke(bean_, EMPTY_ARGS) ;
50     } catch (Exception JavaDoc ex) {
51       return value.getExpression() + " has error: " + ex.getMessage();
52     }
53   }
54   
55   public void setBean(Object JavaDoc bean) {
56     bean_ = bean ;
57   }
58   
59   private Map getMethodMap(Class JavaDoc type) {
60     Map methodMap = (Map)cache_.get(type) ;
61     if(methodMap == null) {
62       synchronized(cache_) {
63         Method JavaDoc[] 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