JavaBean的内省操作 跟反射差不多 ,隻是内省操作比反射簡單,但是原理都一樣, 學會了JavaBean的内省操作 那麼對于JavaBean在web中的應用就會有很好的了解,并且明白為什麼利用動作指令setProperty就可以設定JavaBean的屬性 :
看下面代碼 ,有注釋。
假設我們有一個JavaBean
package me.test;
public class IntroSpectorTest
{
private int x ;
public IntroSpectorTest(int x)
{
this.x=x ;
}
public int getX()
return x ;
public void setX(int x)
}
1、這是對 JavaBean的内省操作(這個隻是我自己寫的代碼
import java.lang.reflect.*;
import java.beans.PropertyDescriptor;
public class JavaBeanTest {
public static void main(String[] args) throws Exception
IntroSpectorTest t=new IntroSpectorTest(3) ; //建立一個JavaBean對象
String propertyName="x"; //我們對x屬性進行内省操作,定義個String類 儲存屬性名字
PropertyDescriptor pt1=new PropertyDescriptor(propertyName,IntroSpectorTest.class) ; //建立一個 屬性描述符類 PropertyDescriptor類 參數是 屬性名字和 JavaBean類的位元組碼
Method m1=pt1.getReadMethod() ; //獲得設定方法的映射類其實跟反射差不多,通過屬性描述符傳回 Method對象 ,這個對象是 getX()方法的映射對象
Object obj=m1.invoke(t); //調用t對象的getX方法,并傳回結果 ,結果自動裝箱
System.out.println(obj); //列印結果
PropertyDescriptor pt2=new PropertyDescriptor(propertyName,IntroSpectorTest.class); //建立屬性描述類
Method m2=pt2.getWriteMethod() ;//獲得設定方法 對應的映射對象
m2.invoke(t, 7); //執行 t對象的setX方法
System.out.println(t.getX()); //列印結果
2、下面是通過Eclipse提供的 Refactor ->Extract Method 提取方法 得到的代碼
import java.beans.IntrospectionException;
import java.beans.Introspector;
IntroSpectorTest t=new IntroSpectorTest(3) ;
String propertyName="x";
Object obj = getProperty(t, propertyName); //看看像不像jsp動作指令中的 setProperty 。。。。這就是JavaBean内省操作
System.out.println(obj);
setProperty(t, propertyName); //看看像不像jsp動作指令中的 setProperty 。。。。這就是JavaBean内省操作
System.out.println(t.getX());
private static void setProperty(IntroSpectorTest t, String propertyName) //利用 Eclipse的Refactor自動為我們生成的方法
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
PropertyDescriptor pt2=new PropertyDescriptor(propertyName,IntroSpectorTest.class);
Method m2=pt2.getWriteMethod() ;//獲得設定方法
m2.invoke(t, 7);
private static Object getProperty(IntroSpectorTest t, String propertyName) //利用 Eclipse的Refactor自動為我們生成的方法
PropertyDescriptor pt1=new PropertyDescriptor(propertyName,IntroSpectorTest.class) ;
Method m1=pt1.getReadMethod() ; //獲得設定方法的映射類其實跟反射差不多
Object obj=m1.invoke(t);
return obj;