1 19 20 package org.apache.cayenne.reflect; 21 22 import java.beans.IntrospectionException ; 23 import java.beans.PropertyDescriptor ; 24 import java.lang.reflect.Method ; 25 26 32 public class BeanAccessor implements Accessor { 33 34 protected String propertyName; 35 protected Method readMethod; 36 protected Method writeMethod; 37 protected Object nullValue; 38 39 public BeanAccessor(Class objectClass, String propertyName, Class propertyType) { 40 if (objectClass == null) { 41 throw new IllegalArgumentException ("Null objectClass"); 42 } 43 44 if (propertyName == null) { 45 throw new IllegalArgumentException ("Null propertyName"); 46 } 47 48 this.propertyName = propertyName; 49 this.nullValue = PropertyUtils.defaultNullValueForType(propertyType); 50 51 try { 52 PropertyDescriptor descriptor = new PropertyDescriptor ( 53 propertyName, 54 objectClass); 55 56 this.readMethod = descriptor.getReadMethod(); 57 this.writeMethod = descriptor.getWriteMethod(); 58 } 59 catch (IntrospectionException e) { 60 throw new PropertyException( 61 "Invalid bean property: " + propertyName, 62 this, 63 e); 64 } 65 } 66 67 public String getName() { 68 return propertyName; 69 } 70 71 74 public Object getValue(Object object) throws PropertyException { 75 if (readMethod == null) { 76 throw new PropertyException("Property '" 77 + propertyName 78 + "' is not readable", this, object); 79 } 80 81 try { 82 return readMethod.invoke(object, null); 83 } 84 catch (Throwable th) { 85 throw new PropertyException( 86 "Error reading property: " + propertyName, 87 this, 88 object, 89 th); 90 } 91 } 92 93 96 public void setValue(Object object, Object newValue) throws PropertyException { 97 98 if (writeMethod == null) { 99 throw new PropertyException("Property '" 100 + propertyName 101 + "' is not writable", this, object); 102 } 103 104 if (newValue == null) { 106 newValue = this.nullValue; 107 } 108 109 try { 110 writeMethod.invoke(object, new Object [] { 111 newValue 112 }); 113 } 114 catch (Throwable th) { 115 throw new PropertyException( 116 "Error reading property: " + propertyName, 117 this, 118 object, 119 th); 120 } 121 } 122 } 123 | Popular Tags |