1 16 17 package org.apache.taglibs.io; 18 19 import java.beans.BeanInfo ; 20 import java.beans.Introspector ; 21 import java.beans.IntrospectionException ; 22 import java.beans.PropertyDescriptor ; 23 import java.lang.reflect.Method ; 24 import java.io.BufferedReader ; 25 import java.io.IOException ; 26 import java.io.InputStream ; 27 import java.io.InputStreamReader ; 28 import java.io.OutputStream ; 29 import java.io.OutputStreamWriter ; 30 import java.io.StringReader ; 31 import java.io.Reader ; 32 import java.io.Writer ; 33 34 import javax.servlet.jsp.JspException ; 35 import javax.servlet.jsp.tagext.Tag ; 36 import javax.servlet.jsp.tagext.TagSupport ; 37 38 43 public class BeanHelper { 44 45 protected static final Object [] NULL_ARGUMENTS = {}; 46 47 54 public static Object getProperty( Object bean, String propertyName ) throws JspException { 55 try { 56 PropertyDescriptor descriptor 57 = getPropertyDescriptor( bean, propertyName ); 58 Method method = descriptor.getReadMethod(); 59 return method.invoke( bean, NULL_ARGUMENTS ); 60 } 61 catch (Exception e) { 62 throw new JspException ( 63 "Failed to get property: " + propertyName 64 + " on bean: " + bean + ". Exception: " + e ); 65 } 66 } 67 68 76 public static void setProperty( Object bean, String propertyName, Object value ) throws JspException { 77 try { 78 PropertyDescriptor descriptor 79 = getPropertyDescriptor( bean, propertyName ); 80 Method method = descriptor.getWriteMethod(); 81 Object [] arguments = { value }; 82 method.invoke( bean, arguments ); 83 } 84 catch (Exception e) { 85 throw new JspException ( 86 "Failed to set property: " + propertyName 87 + " on bean: " + bean + ". Exception: " + e ); 88 } 89 } 90 91 93 protected static PropertyDescriptor getPropertyDescriptor( 94 Object bean, 95 String propertyName 96 ) throws JspException { 97 try { 98 Class beanClass = bean.getClass(); 99 BeanInfo beanInfo = Introspector.getBeanInfo( beanClass ); 100 101 PropertyDescriptor [] descriptors = beanInfo.getPropertyDescriptors(); 103 if ( descriptors != null ) { 104 int size = descriptors.length; 105 for ( int i = 0; i < size; i++ ) { 106 PropertyDescriptor descriptor = descriptors[i]; 107 String name = descriptor.getName(); 108 if ( propertyName.equals( name ) ) { 109 return descriptor; 110 } 111 } 112 } 113 throw new JspException ( 114 "No such property: " + propertyName + " on bean: " + bean 115 ); 116 } 117 catch (IntrospectionException e) { 118 throw new JspException ( 119 "Failed to instrospect bean: " + bean + ". Exception: " + e 120 ); 121 } 122 } 123 } 124 | Popular Tags |