java内省(Introspector)

内省(Introspector) 是Java 语言对 JavaBean 类属性、事件的一种缺省处理方法。

  JavaBean是一种特殊的类,主要用于传递数据信息,这种类中的方法主要用于访问私有的字段,且方法名符合某种命名规则。如果在两个模块之间传递信息,可以将信息封装进JavaBean中,这种对象称为“值对象”(Value Object),或“VO”。方法比较少。这些信息储存在类的私有变量中,通过set()、get()获得

     Java JDK中提供了一套 API 用来访问某个属性的 getter/setter 方法,这就是内省

package com.liang.Instopector;

import java.io.Serializable;
import java.util.Date;

public class Student implements Serializable {
	private String name="liang";
	private int age=21;
	private Date birthday;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	

}

package com.liang.Instopector;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Date;

import org.junit.Test;
public class Demo {
	@Test
	public void test1() throws Exception{
		//获得指定的beanInfo对象
		BeanInfo beanInfo = Introspector.getBeanInfo(Student.class);
		//获得属性描述数组
		PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
		//遍历:因为类继承Object类,Object类中有一个getClass()方法,所以个数会比你写的多一个
		System.out.println(pds.length);
		for(PropertyDescriptor pd:pds){
			System.out.print(pd.getName()+"  ");
		}
		System.out.println();
		//获得指定的PropertyDescriptor
		PropertyDescriptor pd=new PropertyDescriptor("name", Student.class);
		//获得get方法
		Method m=pd.getReadMethod();
		Student s=new Student();
		String str=(String)m.invoke(s, null);
		System.out.println(str);
		//获得set方法
		Method m1=pd.getWriteMethod();
		m1.invoke(s, "aaa");
		System.out.println(s.getName());
	}	
}









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值