1 22 package org.jboss.util.property; 23 24 import org.jboss.util.FieldInstance; 25 import org.jboss.util.NullArgumentException; 26 import org.jboss.util.Classes; 27 import org.jboss.util.ThrowableHandler; 28 import org.jboss.util.propertyeditor.PropertyEditors; 29 30 import java.beans.PropertyEditor ; 31 32 38 public class FieldBoundPropertyListener 39 extends BoundPropertyAdapter 40 { 41 42 protected final String propertyName; 43 44 45 protected final FieldInstance fieldInstance; 46 47 56 public FieldBoundPropertyListener(final Object instance, 57 final String fieldName, 58 final String propertyName) 59 { 60 if (propertyName == null) 61 throw new NullArgumentException("propertyName"); 62 64 this.propertyName = propertyName; 65 66 try { 67 fieldInstance = new FieldInstance(instance, fieldName); 69 try { 70 fieldInstance.getField().setAccessible(true); 71 } 72 catch (SecurityException e) { 73 ThrowableHandler.add(e); 74 } 75 76 Classes.forceLoad(fieldInstance.getField().getType()); 79 } 80 catch (NoSuchFieldException e) { 81 throw new PropertyException(e); 82 } 83 } 84 85 93 public FieldBoundPropertyListener(final Object instance, 94 final String fieldName) 95 { 96 this(instance, fieldName, fieldName); 97 } 98 99 104 public final String getPropertyName() { 105 return propertyName; 106 } 107 108 116 public String filterValue(String value) { 117 return value; 118 } 119 120 127 protected void setFieldValue(String value) { 128 try { 129 value = filterValue(value); 131 132 Class type = fieldInstance.getField().getType(); 134 PropertyEditor editor = PropertyEditors.findEditor(type); 135 editor.setAsText(value); 136 Object coerced = editor.getValue(); 137 138 fieldInstance.set(coerced); 140 } 141 catch (IllegalAccessException e) { 142 throw new PropertyException(e); 143 } 144 } 145 146 151 public void propertyAdded(final PropertyEvent event) { 152 setFieldValue(event.getPropertyValue()); 153 } 154 155 160 public void propertyChanged(final PropertyEvent event) { 161 setFieldValue(event.getPropertyValue()); 162 } 163 164 169 public void propertyBound(final PropertyMap map) { 170 if (map.containsProperty(propertyName)) { 172 setFieldValue(map.getProperty(propertyName)); 173 } 174 } 175 } 176 | Popular Tags |