使用内省的方式操作JavaBean

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 使用内省的方式操作JavaBean
 */
public class IntroSpectorTest {

	public static void main(String[] args) throws Exception {
		ReflectPoint reflectPoint = new ReflectPoint(3,7);
		
		//调用JavaBean中方法的传统作法
		Class classz = reflectPoint.getClass();
		Field[] fields = classz.getDeclaredFields();
		for (Field field : fields) {
			String name = "set" + field.getName().toUpperCase();
			Method method = classz.getMethod(name, int.class);
			method.invoke(reflectPoint, 3);
		}
		System.out.println(reflectPoint);
		
		//使用内省的方式调用JavaBean的方法
		String propertyName = "x";
		//获得属性x的值
		Object retVal = getProperty2(reflectPoint, propertyName);
		System.out.println(retVal);
		//设置属性x的值
		setProperty(reflectPoint, propertyName,10);
		System.out.println(reflectPoint.getX());
		
	}

	/**
	 * 设置属性的值
	 * @param obj 属性所属的对象
	 * @param propertyName 属性名
	 * @param propertyValue 属性值
	 */
	private static void setProperty(Object obj, String propertyName,Object propertyValue) throws Exception {
		PropertyDescriptor pd2 = new PropertyDescriptor(propertyName,obj.getClass());
		Method setMethod = pd2.getWriteMethod();
		setMethod.invoke(obj, propertyValue);
	}

	/**
	 * 获得对象的属性值
	 * @param obj 属性所属的对象
	 * @param propertyName 属性名
	 * @return 属性的值
	 */
	private static Object getProperty(Object obj, String propertyName) throws Exception {
		PropertyDescriptor pd = new PropertyDescriptor(propertyName,obj.getClass());
		Method getMethod = pd.getReadMethod();	//获得get方法
		Object retVal = getMethod.invoke(obj);
		return retVal;
	}
	
	/**
	 * 使用内省操作javabean
	 * @param obj 属性所属的对象
	 * @param propertyName 属性名
	 * @return 属性的值
	 */
	private static Object getProperty2(Object obj, String propertyName) throws Exception {
		Object retVal = null;
		BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
		PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
		for (PropertyDescriptor pd : pds) {
			if (pd.getName().equals(propertyName)) {
				Method getMethod = pd.getReadMethod();
				retVal = getMethod.invoke(obj);
				break;
			}
		}
		return retVal;
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xyang0917

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值