IntroSpector内省

package com.interview.introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
public class IntroSpector {
	public static void main(String[] args){
		 //ID号  姓名  年龄
		Person person = new Person(0001, "张三", 23);
		//通过属性名操作set get方法
		String propertyName = "name";
		Object retVal = getProperty(person, propertyName);
		System.out.println("通过get方法得到的值为:"+retVal);
		
		setProperty(person , propertyName , "李四");
		System.out.println("set方法后的值为:"+getProperty(person, propertyName));
	}

	/**
	 * 通过反射技术得到属性的get方法,并返回相应的值
	 * @param obj 要调用的对象
	 * @param propertyName 属性名
	 * @return 属性值
	 */
	private static Object getProperty(Object obj, String propertyName) {
		Object retVal = null ;
		try {
			/**--------方法一 --------------**/
			PropertyDescriptor descriptor = new PropertyDescriptor(propertyName, obj.getClass());
			//得到get方法
			Method readMethod = descriptor.getReadMethod();
			//执行get方法得到值,提供相应的类以及要传递的字段值
			retVal = readMethod.invoke(obj, null);
			/**-----------方法二-------------- **/
			//得到所有属性的descriptor
//			PropertyDescriptor[] descriptors = Introspector.getBeanInfo(obj.getClass()).getPropertyDescriptors();
//			//遍历得到相应的descriptor
//			for(PropertyDescriptor des : descriptors){
//				if(des.getName().equals(propertyName)){
//					Method readMethod = des.getReadMethod();
//					retVal = readMethod.invoke(obj, null);
//					break;
//				}
//			}
		} catch (Exception e) {
			System.out.println("属性值不存在!");
		}
		return retVal;
	}
	
	
	/**
	 * 通过属性名,利用反射技术,得到属性的set方法,来set新值
	 * @param obj 要调用的对象
	 * @param propertyName 属性名
	 * @param propertyValue 要设置的属性值
	 */
	private static void setProperty(Object obj, String propertyName, String propertyValue) {
		try {
			PropertyDescriptor descriptor = new PropertyDescriptor(propertyName, obj.getClass());
			//得到get方法
			Method writeMethod = descriptor.getWriteMethod();
			//执行get方法得到值,提供相应的类以及要传递的字段值
			writeMethod.invoke(obj, propertyValue);
		} catch (Exception e) {
			System.out.println("属性值不存在!");
		}
	}
}

来自张孝祥老师---31_对JavaBean的复杂内省操作


最后介绍了BeanUtils, PropertyUtils工具包使用,但是只有在java se项目中能使用,java web 项目报错,不知道什么原因!!!

要引入的包为:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值