国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

【JavaEE】Java內(nèi)省Introspector、PropertyDescriptor與JavaBean

2019-11-11 06:48:50
字體:
供稿:網(wǎng)友

1.java內(nèi)省概念

Sun公司開發(fā)了一套API,專門用于操作Java對象的屬性。【Introspector】 在開發(fā)框架時,需要使用Java對象的屬性來封裝程序的數(shù)據(jù),使用反射技術完成此類操作過于麻煩,我們使用內(nèi)省。 內(nèi)省(Introspector) 是Java 語言對 JavaBean 類屬性、事件的一種缺省處理方法。

JavaBean是一種特殊的類,主要用于傳遞數(shù)據(jù)信息,這種類中的方法主要用于訪問私有的字段,且方法名符合某種命名規(guī)則。 如果在兩個模塊之間傳遞信息,可以將信息封裝進JavaBean中,這種對象稱為”值對象”(Value Object),或”VO”。 方法比較少。這些信息儲存在類的私有變量中,通過set()、get()獲得。 在Student中有屬性name, age, birthday。我們可以通過getName, setName來訪問name屬性,這就是默認的規(guī)則。 Java JDK中提供了一套 API 用來訪問某個屬性的 getter/setter 方法,這就是內(nèi)省。 PRopertyDescriptor類: PropertyDescriptor類表示JavaBean類通過存儲器導出一個屬性。主要方法: 1. getReadMethod(),獲得用于讀取屬性值的方法; 2. getWriteMethod(),獲得用于寫入屬性值的方法; 3. setReadMethod(Method readMethod),設置用于讀取屬性值的方法; 4. setWriteMethod(Method writeMethod),設置用于寫入屬性值的方法。

通過PropertyDescriptor與Introspector的比較可以看出,都是需要獲得PropertyDescriptor,只是方式不一樣: PropertyDescriptor通過創(chuàng)建對象直接獲得,Introspector需要遍歷, 所以使用PropertyDescriptor類更加方便。

Introspector類,將JavaBean中的屬性封裝起來進行操作。 1.在程序中把一個類當做JavaBean來看,調(diào)用Introspector.getBeanInfo()方法, 得到的BeanInfo對象封裝了這個類的屬性信息。 2.通過BeanInfo來獲取屬性的屬性描述器PropertyDescriptor 。

3.通過PropertyDescriptor獲取某個屬性對應的getter/setter方法, 然后通過反射機制來調(diào)用這些方法。

BeanInfo bi = Introspector.getBeanInfo(Student.class); PropertyDescriptor [] pds = bi.getPropertyDescriptors();

BeanUtils工具包 內(nèi)省操作非常的繁瑣,所以所以Apache開發(fā)了一套簡單、易用的API來操作Bean的屬性,BeanUtils工具包。 beanutils內(nèi)省框架(依賴commons-logging):apache 準備包:commons-beanutils.jar, commons-logging.jar BeanUtils工具包: 下載:commons-beanutils.jar http://commons.apache.org/beanutils/  commons-logging.jar http://commons.apache.org/logging/

1.獲得屬性的值,例如,BeanUtils.getProperty(stu,”stuName”),返回字符串 2.設置屬性的值,例如,BeanUtils.setProperty(stu,”age”,38),參數(shù)是字符串或基本類型自動包裝。 設置屬性的值是字符串,獲得的值也是字符串,不是基本類型。    3.BeanUtils的特點: ①對基本數(shù)據(jù)類型的屬性的操作:String<—–>基本類型 在WEB開發(fā)、使用中,錄入和顯示時,值會被轉(zhuǎn)換成字符串,但底層運算用的是基本類型,這些類型轉(zhuǎn)到動作由BeanUtils自動完成。 ②非基本類型的屬性的操作:String<—-> 其他類型 例如:

public void test5 () throws Exception{ Student s = new Student (); //給BeanUtils注冊轉(zhuǎn)換器, ConvertUtils.register(new Converter (){ //type是目標類型, value是當前傳入的值 public Object convert(Class type, Object value) { DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); //字符串轉(zhuǎn)換為Date String v= (String) value; try{ Date d = df.parse(v); return d; }catch (ParseException e){ throw new RuntimeException (e); } } }, Date.class); BeanUtils.setProperty(s, "birthday", "1990-08-25"); System.out.println(s.getBirthday()); } /** * 給BeanUtils注冊轉(zhuǎn)換器,參數(shù):converter 要注冊的轉(zhuǎn)換器 * clazz 此轉(zhuǎn)換器執(zhí)行的轉(zhuǎn)換的目標類 */ public static void register(Converter converter, Class clazz); public interface Converter { /* *將特定輸入轉(zhuǎn)換成特定的輸出類型 *參數(shù):type 目標轉(zhuǎn)換類型,value 待轉(zhuǎn)換的輸入值 *返回值: 轉(zhuǎn)換的結果 */ public Object convert(Class type, Object value);}

2. Java內(nèi)省實例

JavaBean

package cn.edu;import java.util.Date;public class Student { private String stuName; private int age; private Date birthday; public String getStuName() { return stuName; } public void setStuName(String stuName) { this.stuName = stuName; } 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; } @Override public String toString() { return "Student [stuName=" + stuName + ", age=" + age + ", birthday=" + birthday + "]"; }}package cn.edu;import java.beans.BeanInfo;import java.beans.Introspector;import java.beans.PropertyDescriptor;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.text.DateFormat;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;import org.apache.commons.beanutils.BeanUtils;import org.apache.commons.beanutils.ConvertUtils;import org.apache.commons.beanutils.Converter;import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;public class BeanInfoUtil { public static void main(String[] args) throws Exception { Student stu = new Student(); BeanInfoUtil.setProperty(stu, "stuName","Tom"); BeanInfoUtil.getProperty(stu, "stuName"); setPropertyByIntrospector(stu, "stuName","Ben"); getPropertyByIntrospector(stu, "stuName"); /* * 3.BeanUtils工具包操作JavaBean * */ BeanUtils.setProperty(stu, "stuName", "Green"); BeanUtils.setProperty(stu, "age", 18); System.out.println("get stuName:"+BeanUtils.getProperty(stu, "stuName")); System.out.println("get age:"+BeanUtils.getProperty(stu, "age")); convertUtilsGetBirthday(stu, "1990-08-25"); convertUtilsGetBirthday2(stu, "1993-08-25"); } /** * 1.直接通過 PropertyDescriptor類的操作Bean屬性 * */ public static void setProperty(Student stu, String stuName, String value) throws Exception, IllegalArgumentException, InvocationTargetException{ //1.獲取stuName屬性 PropertyDescriptor propDesc=new PropertyDescriptor(stuName,Student.class); //2.得到setStuName()方法 Method methodSetStuName=propDesc.getWriteMethod(); //3.調(diào)用setStuName()方法 methodSetStuName.invoke(stu, value); System.out.println("set name:"+stu.getStuName()); } public static void getProperty(Student stu, String stuName) throws Exception{ PropertyDescriptor proDescriptor =new PropertyDescriptor(stuName,Student.class); Method methodGetStuName=proDescriptor.getReadMethod(); Object objStuName=methodGetStuName.invoke(stu); System.out.println("get name:"+objStuName.toString()); } /** *  2.通過Introspector類獲取BeanInfo對象,再通過BeanInfo獲取PropertyDescriptor,操作Bean屬性 * */ public static void setPropertyByIntrospector(Student stu,String stuName, String value)throws Exception{ //1.獲取BeanInfo對象 BeanInfo beanInfo=Introspector.getBeanInfo(Student.class); //2.通過BeanInfo對象獲取PropertyDescriptor PropertyDescriptor[] proDescrtptors=beanInfo.getPropertyDescriptors(); //3.遍歷 if(proDescrtptors !=null && proDescrtptors.length > 0){ for(PropertyDescriptor propDesc : proDescrtptors){ if(propDesc.getName().equals(stuName)){ Method methodSetUserName=propDesc.getWriteMethod(); methodSetUserName.invoke(stu, value); System.out.println("set stuName:"+stu.getStuName()); break; } } } } public static void getPropertyByIntrospector(Student stu,String stuName)throws Exception{ BeanInfo beanInfo=Introspector.getBeanInfo(Student.class); PropertyDescriptor[] proDescrtptors=beanInfo.getPropertyDescriptors(); if(proDescrtptors !=null && proDescrtptors.length > 0){ for(PropertyDescriptor propDesc : proDescrtptors){ if(propDesc.getName().equals(stuName)){ Method methodStuUserName=propDesc.getReadMethod(); Object objStuName=methodStuUserName.invoke(stu); System.out.println("get StuName:"+objStuName.toString()); break; } } } } /** * 給BeanUtils注冊時間日期轉(zhuǎn)換器 * */ public static void convertUtilsGetBirthday(Student stu, String date) throws Exception{ //給BeanUtils注冊轉(zhuǎn)換器, type是目標類型, value是當前傳入的值 ConvertUtils.register(new Converter (){ public Object convert(Class type, Object value) { DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); //字符串轉(zhuǎn)換為Date String v= (String) value; try{ Date d = df.parse(v); return d; }catch (ParseException e){ throw new RuntimeException (e); } } }, Date.class); BeanUtils.setProperty(stu, "birthday", date); System.out.println(stu.getBirthday()); } /** * 給BeanUtils注冊時間日期轉(zhuǎn)換器 * */ public static void convertUtilsGetBirthday2(Student stu, String date) throws Exception{ ConvertUtils.register(new DateLocaleConverter(), Date.class); BeanUtils.setProperty(stu, "birthday", date); System.out.println(stu.getBirthday()); } }/* set name:Tom get name:Tom set stuName:Ben get StuName:Ben get stuName:Green get age:18 Sat Aug 25 00:00:00 CDT 1990 Wed Aug 25 00:00:00 CST 1993 * */

3.Java封裝客戶端請求參數(shù)至JavaBean

JavaBeanpublic class User { private String username; private String passWord[]; private String gender; public String getUsername() {//讀屬性,屬性名稱username return username; } public void setUsername(String username) {//寫屬性,屬性名username this.username = username; } public String[] getPassword() { return password; } public void setPassword(String[] password) { this.password = password; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } @Override public String toString() { return "User [username=" + username + ", password=" + Arrays.toString(password) + ", gender=" + gender + "]"; }}

封裝請求參數(shù)的幾種方案:

/*1.使用Java內(nèi)省,將請求參數(shù)的值封裝到JavaBean中。 約定優(yōu)于編碼:表單的輸入域的name取值和JavaBean中的屬性(getter和setter方法)保持一致 */ private void test1(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Enumeration<String> e = request.getParameterNames();//參數(shù)名 User user = new User(); while(e.hasMoreElements()){ String paramName = e.nextElement();//即是JavaBean中的屬性名稱 String paramValue = request.getParameter(paramName); //JavaBean的內(nèi)省 try { PropertyDescriptor pd = new PropertyDescriptor(paramName, User.class); Method m = pd.getWriteMethod();//setter方法 m.invoke(user, paramValue); } catch (Exception e1) { e1.printStackTrace(); } } } /*2.getParameterMap獲取參數(shù)*/ private void test6(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //key:請求參數(shù)名 value:請求參數(shù)值數(shù)組 Map<String,String[]> map = request.getParameterMap(); for(Map.Entry<String, String[]> me:map.entrySet()){ System.out.println(me.getKey()+"="+Arrays.asList(me.getValue())); } } /* 3.getParameterMap獲取參數(shù)結合Java 內(nèi)省,封裝到JavaBean中 */ private void test2(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //key:請求參數(shù)名 value:請求參數(shù)值數(shù)組 Map<String,String[]> map = request.getParameterMap(); User user = new User(); for(Map.Entry<String, String[]> me:map.entrySet()){ String paramName = me.getKey();//參數(shù)名稱 String paramValues[] = me.getValue();//參數(shù)值 try { PropertyDescriptor pd = new PropertyDescriptor(paramName, User.class); Method m = pd.getWriteMethod();//setter方法 if(paramValues.length > 1){ m.invoke(user, (Object)paramValues); }else{ m.invoke(user, paramValues); } } catch (Exception e1) { e1.printStackTrace(); } } } /*3.借助第三方工具包:借助BeanUtil框架*/ private void test8(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { User user = new User(); try { BeanUtils.populate(user, request.getParameterMap()); } catch (Exception e) { e.printStackTrace(); } }
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 大姚县| 吉安县| 日照市| 中方县| 西宁市| 江油市| 隆安县| 车险| 五河县| 商河县| 衡东县| 五家渠市| 永吉县| 辽中县| 阿拉善左旗| 丘北县| 毕节市| 永新县| 石嘴山市| 荔波县| 靖州| 伊金霍洛旗| 香河县| 泰和县| 周口市| 延安市| 焉耆| 霍州市| 南雄市| 义马市| 常山县| 吐鲁番市| 习水县| 和平县| 应用必备| 揭西县| 遵义市| 类乌齐县| 淅川县| 淳安县| 阿拉善左旗|