内省

本文深入探讨JavaBean的内省机制,介绍核心类PropertyDescriptor的功能及其API使用方法。通过示例展示如何通过PropertyDescriptor操作JavaBean的属性,并解释了内省与参数类型、BeanInfo的关系。
本质就是反射.
是由sun公司提供,集成到jdk。
核心类:
PropertyDescriptor - 属性描述器
API:
PropertyDescriptor 描述 Java Bean 通过一对存储器方法导出的一个属性。
以下javaBean拥有get and set就是一对,就可以通过PropertyDescorptor来操作。

JavaBean的定义
拥有无参数构造。
拥有一个get | set | isXxxx方法。

如果希望被内省使用
必须
拥有元参数构造
拥有一对get && setXxx | isXxxx方法

以示示例演示如何用操作:
PropertyDescriptor.getReadMethod() - 获取某个Bean中的getXxxx

PropertyDescriptor.getWriteMethod() – 某个bean setXxxx方法。


public void demo1() throws Exception{
		//第一个类
		User o = new User();
//		Method setName = o.getClass().getMethod("setName",String.class);
//		setName.invoke(o, "Jack");
//		System.err.println(o);
//		
		//以下通过内省实现
		PropertyDescriptor pd = 
				new PropertyDescriptor("name",o.getClass(),"getMyName","setName");
		//获取设置属性方法
		/**
		 * getReadMethod = getXxxx
		 * getWriteMethod = setXxxx
		 */
		Method setMethod= pd.getWriteMethod();
		setMethod.invoke(o,"Rose");
		System.err.println(">>:"+o);
		
	}

内省与参数类型

	
@Test
	public void demo1() throws Exception{
		//第一个类
		User o = new User();
		PropertyDescriptor pd = 
				new PropertyDescriptor("age", o.getClass());
		Method m = pd.getWriteMethod();
		m.invoke(o,90);//接收的Integer
		System.err.println(">>:"+o);
		
	}

内省与BeanInfo

	BeanInfo专门用于分析一个Bean拥有多少属性:
/**
	 * 通过Beaninfo获取一个类的所有setXxx|getXxx|isXxx方法 
	 */
	@Test
	public void beaninfo() throws Exception{
		BeanInfo info = 
				Introspector.getBeanInfo(User.class);
		PropertyDescriptor[] pd = info.getPropertyDescriptors();
		for(PropertyDescriptor p:pd){
			String name = p.getName();
			System.err.println(name);
//			Method m =  p.getWriteMethod();//setXxx(....);
//			Class<?>[] cls = m.getParameterTypes();
//			System.err.println(cls.length);
		}
	}

遍历方法

public class MethodReflect {
	public static void main(String[] args) throws Exception {
		String name = "name";
		String value = "90";
		A a = new A();
		Method[] ms = a.getClass().getDeclaredMethods();
		for(Method m:ms){
			String nm = m.getName();//setName
			System.err.println(nm);
			if(nm.startsWith("set")){
				Class<?>[] clss = m.getParameterTypes();
				System.err.println(clss[0]);
				if(clss[0].equals(String.class)){
					m.invoke(a,value);
				}else if(clss[0].equals(Integer.class)){
					m.invoke(a,Integer.valueOf(value));
				}
			}
		}
		System.err.println(a);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值