org.apache.commons.beanutils.BeanMap簡單使用例子


一、 org.apache.commons.beanutils.BeanMap;
將一個java bean允許通過map的api進行調用,

幾個支持的操作接口:

  • Object get(Object key)
  • Object put(Object key, Object value)
  • void putAll(Map t)
  • Set entrySet()
  • Collection values()
  • boolean containsKey(Object key)
  • ....
例如:
//將student的信息拼成字符串,格式:stuname|stuage|stuclass
protected String getLine(Student student ) {
           StringBuilder sb = new StringBuilder();
           BeanMap map = new BeanMap( student );
           appStr(sb, map, "stuname" );
           appStr(sb, map, "stuage" );
           appStr(sb, map, "stuclass" );
            return sb.toString();
     }
 
//將teacher的信息拼成字符串,格式:tname|tage|tclass
protected String getLine(Teacher teacher ) {
           StringBuilder sb = new StringBuilder();
           BeanMap map = new BeanMap(teacher );
           appStr(sb, map, "tname" );
           appStr(sb, map, "tage" );
           appStr(sb, map, "tclass" );
            return sb.toString();
     }
     
 
//拼字符串公用方法,將不同的對象,比如studengt和teacher的信息通過map傳到方法里
protected void appStr(StringBuilder sb, Map<String, Object> map,
                String str) {
           Object value = map.get(str);
           sb.append(newValue).append( "|" );
     }
 
 
注意:在上面的例子中,雖然可以直接用
sb.append(student.getStuname()).append("|").append(student.getStuage()).append("|").append(student.getStuclass);
來拼接字符串,但卻使用了BeanMap,我認為原因就在於同時有多個對象(如student、teacher等)需要用到拼接字符串的方法,
想要抽象出公共的方法,因此使用了BeanMap ,這樣不需要將沒個對象都傳到appStr中,只需要傳一個BeanMap對象就可以了。
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM