1 35 36 package groovy.lang; 37 38 39 import org.codehaus.groovy.runtime.InvokerHelper; 40 import java.lang.reflect.Field ; 41 42 48 public class MetaFieldProperty extends MetaProperty { 49 50 private Field field; 51 52 public MetaFieldProperty(Field field) { 53 super(field.getName(), field.getType()); 54 55 this.field = field; 56 } 57 58 62 public Object getProperty(Object object) throws Exception { 63 return field.get(object); 64 } 65 66 73 public void setProperty(Object object, Object newValue) { 74 try { 75 field.set(object, newValue); 76 } 77 catch (IllegalArgumentException e) { 78 try { 79 field.set(object, InvokerHelper.asType(newValue, field.getType())); 80 } 81 catch (Exception ex) { 82 throw new TypeMismatchException( "'" + toName(object.getClass()) + "." + field.getName() 83 + "' can not refer to the value '" 84 + newValue + "' (type " + toName(newValue.getClass()) 85 + "), because it is of the type " + toName(field.getType()) ); 86 } 87 } 88 catch (Exception e) { 89 throw new GroovyRuntimeException("Cannot set the property '" + name + "'.", e); 90 } 91 } 92 93 private String toName(Class c) { 94 String s = c.toString(); 95 if (s.startsWith("class ") && s.length() > 6) 96 return s.substring(6); 97 else 98 return s; 99 } 100 } 101 | Popular Tags |