java bean简单内省操作

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);

}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值