View Javadoc

1   package net.sf.morph.reflect.reflectors;
2   
3   import org.apache.commons.beanutils.DynaBean;
4   import org.apache.commons.beanutils.DynaProperty;
5   
6   /**
7    * @author Matt Sgarlata
8    * @since Nov 20, 2004
9    */
10  public class DynaBeanReflector extends BaseBeanReflector {
11  	
12  	public static final String IMPLICIT_PROPERTY_DYNA_CLASS = "dynaClass";
13  	
14  	private static final Class[] REFLECTABLE_TYPES =
15  		new Class[] { DynaBean.class };
16  
17  	public DynaBeanReflector() {
18  		super();
19  	}
20  	private DynaBean getDynaBean(Object bean) {
21  		return (DynaBean) bean;
22  	}
23  
24  	protected String[] getPropertyNamesImpl(Object bean) throws Exception {
25  		// note that we are not removing the "class" implicit property because
26  		// there is no way to tell if this was an explicitly defined property
27  		// of the DynaBean or if it was just included because of reflection
28  		DynaProperty[] properties = getDynaBean(bean).getDynaClass().getDynaProperties();
29  		String[] propertyNames = new String[properties.length]; 
30  		for (int i = 0; i < properties.length; i++) {
31  			propertyNames[i] = properties[i].getName();
32  		}
33  		return propertyNames;
34  	}
35  
36  	protected Class getTypeImpl(Object bean, String propertyName) throws Exception {
37  		try {
38  			return getDynaBean(bean).getDynaClass().getDynaProperty(propertyName).getType();
39  		}
40  		// this is inelegant, but the DynaBean API isn't very expressive
41  		// so there's not much we can do
42  		catch (Exception e) {
43  			return Object.class;
44  		}		
45  	}
46  
47  	protected boolean isReadableImpl(Object bean, String propertyName)
48  		throws Exception {
49  		// any property of the bean, including implicit properties, are assumed
50  		// to be readable, because there is no API in BeanUtils to determine
51  		// otherwise
52  		return
53  			IMPLICIT_PROPERTY_DYNA_CLASS.equals(propertyName) ||
54  			super.isReadableImpl(bean, propertyName);
55  	}
56  
57  	protected Object getImpl(Object bean, String propertyName) throws Exception {
58  		DynaBean dyna = getDynaBean(bean);
59  		return IMPLICIT_PROPERTY_DYNA_CLASS.equals(propertyName) ? dyna.getDynaClass() : dyna.get(propertyName);
60  	}
61  
62  	protected void setImpl(Object bean, String propertyName, Object value)
63  		throws Exception {
64  		getDynaBean(bean).set(propertyName, value);
65  	}
66  
67  	public Class[] getReflectableClassesImpl() {
68  		return REFLECTABLE_TYPES;
69  	}
70  
71  }