Home  >  Article  >  Java  >  Java beans call instances through map's api

Java beans call instances through map's api

零下一度
零下一度Original
2017-07-20 14:18:531800browse
1. org.apache.commons.beanutils.BeanMap;
Allows a java bean to be called through the map api,

Several Supported operation interfaces:

  • Object get(Object key)

  • Object put(Object key, Object value)

  • void putAll(Map t)

  • Set entrySet()

  • Collection values()

  • boolean containsKey(Object key)

  • ....

For example :
##
//将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("|");
     }
Note: In the above example, although

can be used directly

sb.append(student.getStuname()).append("|").append(student.getStuage()).append("|").append(student.getStuclass);

To splice strings, but use BeanMap. I think the reason is that there are multiple objects (such as student, teacher, etc.) that need to use the method of splicing strings at the same time.

I want to abstract the public method , so BeanMap is used, so there is no need to pass every object to appStr, only one BeanMap object is required.

The above is the detailed content of Java beans call instances through map's api. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn