黑馬程序員_javaBean的內省操作

---------------------- android培訓java培訓、期待與您交流! ----------------------

 什麼是javabean呢?舉個例子說明一下

package bean;

public class Student {

		private String name;
		private Integer age;
		
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public Integer getAge() {
			return age;
		}
		public void setAge(Integer age) {
			this.age = age;
		}
}


符合以上規範的java類就可以說是一個javabean了。

什麼是javabean的內省呢?內省就是操作javabean的api。

一個簡單的例子:通過內省操作,對Student類中的屬性賦值並且顯示屬性值

package bean;

import java.beans.PropertyDescriptor;

public class MyBean {

	/**
	 * @param args
	 */
	public static void main(String[] args)throws Exception {

		String propertyName1="age";	//javabean中的age屬性
		String propertyName2="name";//javabean中的name屬性
		Student stu=new Student();
		PropertyDescriptor pd1=new PropertyDescriptor(propertyName1,stu.getClass());
		PropertyDescriptor pd2=new PropertyDescriptor(propertyName2,stu.getClass());
		pd1.getWriteMethod().invoke(stu, 12);
		pd2.getWriteMethod().invoke(stu, "Jim");
		System.out.println(pd1.getReadMethod().invoke(stu));
		System.out.println(pd2.getReadMethod().invoke(stu));
	}

}

這就是一個javabean的簡單內省操作。

複雜的javabean內省操作是使用BeanInfo和Introspector這個類來完成的

範例:

package bean;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;

public class MyBean {

	/**
	 * @param args
	 */
	public static void main(String[] args)throws Exception {

		String propertyName1="age";	//javabean中的age屬性
		String propertyName2="name";//javabean中的name屬性
		Student stu=new Student();
		PropertyDescriptor pd1=new PropertyDescriptor(propertyName1,stu.getClass());
		PropertyDescriptor pd2=new PropertyDescriptor(propertyName2,stu.getClass());
		pd1.getWriteMethod().invoke(stu, 12);
		pd2.getWriteMethod().invoke(stu, "Jim");
		System.out.println(getProperty(stu,propertyName1));
	}
	//使用複雜內省操作得到屬性值
	public static Object getProperty(Student stu,String propertyName) throws Exception
	{
		BeanInfo bean=Introspector.getBeanInfo(stu.getClass());
		PropertyDescriptor[] pds=bean.getPropertyDescriptors();
		Object reValue=null;
		for(PropertyDescriptor pd:pds)
		{
			if(pd.getName().equals(propertyName))
			{
				reValue=pd.getReadMethod().invoke(stu);
				break;
			}
		}
		return reValue;
	}

}



 

 

---------------------- android培訓java培訓、期待與您交流! ----------------------

詳細請查看:http://edu.csdn.net/heima

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章