Java基礎複習:JavaBean和Java內省API

來源:互聯網
上載者:User

關於JavaBean:符合特定規則的類(JavaBean只是一個規範而已!)

    (1)私人的欄位(private Field)

    (2)對私人欄位提供存取方法(getter/setter)

    (3)數量任意的業務方法

 

內省(IntroSpector)是java對Bean類屬性、事件的一種預設處理方法。即通過getter/setter來訪問屬性。Java 中提供了一套 API 用來訪問某個屬性的 getter/setter 方法,通過這些 API 可以使你不需要瞭解這個規則(但你最好還是要搞清楚),這些 API 存放於包 java.beans 中,一般的做法是通過類 Introspector 的 getBeanInfo方法 來擷取某個對象的 BeanInfo 資訊,然後通過 BeanInfo 來擷取屬性的描述器(PropertyDescriptor),通過這個屬性描述器就可以擷取某個屬性對應的
getter/setter 方法,然後我們就可以通過反射機制來調用這些方法。

 

訪問JavaBean屬性的兩種方式:

1)直接調用bean的getter/setter方法

2)通過內省技術訪問(java.beans包中)

 

Student類

package web.java.introspector;public class Student {private String name;private String sno;public String getName() {return name;}public String getSno() {return sno;}public void setName(String name) {this.name = name;}public void setSno(String sno) {this.sno = sno;}/* * 屬性和欄位是不同的: * 欄位是在類最上面聲明的變數或常量部分 * 屬性是getXxx/setXxx後面的Xxx * 顯然這裡的age也是屬性 */public int getAge() {return 21;}}

測試類別:(這裡使用Junit進行測試)

package web.java.introspector;import java.beans.BeanInfo;import java.beans.Introspector;import java.beans.PropertyDescriptor;import java.lang.reflect.Method;import org.junit.Test;public class Demo1 {@Testpublic void test1() throws Exception {Student s1 = new Student();/* * 1. 通過PropertyDescriptor類操作Bean的屬性  */PropertyDescriptor pd = new PropertyDescriptor("name", Student.class);Method m = pd.getWriteMethod();m.invoke(s1, "well");m = pd.getReadMethod();String returnValue = (String)m.invoke(s1, null);System.out.println(returnValue);}/* * 通過Introspector類獲得Bean對象的 BeanInfo, * 然後通過 BeanInfo 來擷取屬性的描述器( PropertyDescriptor ), * 通過這個屬性描述器就可以擷取某個屬性對應的 getter/setter 方法, * 然後通過反射機制來調用這些方法。 */@Testpublic void test2() throws Exception {//BeanInfo表示該Student對象所有的屬性情況BeanInfo bi = Introspector.getBeanInfo(Student.class);//取得Student對象所有屬性集合PropertyDescriptor[] pds = bi.getPropertyDescriptors();for (PropertyDescriptor pd : pds) {System.out.println(pd.getName());//輸出age class name sno}}}

 

值得注意的是:任何一個JavaBean都有一個class屬性,來自於Object類。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.