1 package com.google.code.beanmatchers; 2 3 import static com.google.code.beanmatchers.BeanOperations.instantiateBean; 4 import static com.google.code.beanmatchers.BeanOperations.invokeGetter; 5 import static com.google.code.beanmatchers.BeanOperations.invokeSetter; 6 import static com.google.code.beanmatchers.BeanOperations.propertyDescriptors; 7 8 import java.beans.PropertyDescriptor; 9 import java.util.List; 10 11 class JavaBean { 12 13 private final Object targetBean; 14 private final PropertyDescriptor[] descriptors; 15 16 public JavaBean(Object targetBean) { 17 this.targetBean = targetBean; 18 descriptors = propertyDescriptors(targetBean); 19 } 20 21 public JavaBean(Class targetBeanType) { 22 this(instantiateBean(targetBeanType)); 23 } 24 25 public Class beanType() { 26 return targetBean.getClass(); 27 } 28 29 public Class<?> propertyType(String propertyName) { 30 return descriptorForName(propertyName).getPropertyType(); 31 } 32 33 public void setProperty(String propertyName, Object value) { 34 invokeSetter(targetBean, descriptorForName(propertyName), value); 35 } 36 37 public Object getProperty(String propertyName) { 38 return invokeGetter(targetBean, descriptorForName(propertyName)); 39 } 40 41 private PropertyDescriptor descriptorForName(String propertyName) { 42 for (PropertyDescriptor propertyDescriptor : descriptors) { 43 if (propertyDescriptor.getName().equals(propertyName)) { 44 return propertyDescriptor; 45 } 46 } 47 throw new BeanMatchersException( 48 "No property named '" + propertyName + "' on bean " + targetBean); 49 } 50 51 public List<String> properties() { 52 return BeanOperations.properties(descriptors); 53 } 54 55 public String toString() { 56 return targetBean.toString(); 57 } 58 59 @Override 60 public int hashCode() { 61 return targetBean.hashCode(); 62 } 63 64 @Override 65 public boolean equals(Object object) { 66 if (object instanceof JavaBean) { 67 return targetBean.equals(((JavaBean) object).targetBean); 68 } else { 69 return targetBean.equals(object); 70 } 71 } 72 }