package introSpector;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.junit.Test;
/**
* java自带的api可以直接对java bean对象进行get/set操作
* @author lxf
*
*/
public class Learn {
@Test
public void test_1() throws Exception{
ReflectPoint rp = new ReflectPoint();
String property = "x";
String property2 = "detail";
writeProperty(rp,property,123);
System.out.println(this.getProperty(rp, property));
writeProperty(rp,property2,"detail content");
System.out.println(this.getProperty(rp, property2));
}
/**
* param object 对象
* param property 属性名
*/
private Object getProperty(Object object, String property) throws IntrospectionException,
IllegalAccessException, IllegalArgumentException,
InvocationTargetException {
PropertyDescriptor pd = new PropertyDescriptor(property,object.getClass());
Method readMethod = pd.getReadMethod();
Object r = readMethod.invoke(object);
return r;
}
/**
* param object 对象
* param property 属性名
* param propertyValue 属性值
*/
private void writeProperty(Object object, String property,Object propertyValue)
throws IntrospectionException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
PropertyDescriptor pd = new PropertyDescriptor(property,object.getClass());
Method writeMethod = pd.getWriteMethod();
writeMethod.invoke(object, propertyValue);
}
}
评论