运用PropertyUtils 将javaBean转化成Mapalibaba - 超凡娱乐

运用PropertyUtils 将javaBean转化成Mapalibaba

2018-09-09 11:05:58 | 作者: 南莲 | 标签: 特点,类型 | 浏览: 7603

https://hi.baidu.com/303132376/item/adfebff703f0132e753c4c10
需求导入commons-beanutils.jar  和 commons-logging.jar
下面是两个javaBean
Author.java
package com.beanUtil;
public class Author {
 private String name;
 public Author() {
 super();
 public String getName() {
 return name;
 public void setName(String name) {
 this.name = name;
}

Book.java
package com.beanUtil;
public class Book {
 private String name;
 private Author author;
 public String getName() {
 return name;
 public void setName(String name) {
 this.name = name;
 public Author getAuthor() {
 return author;
 public void setAuthor(Author author) {
 this.author = author;
}

Bean2Map.java
package com.beanUtil;
import java.util.Map;
import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.PropertyUtils;
public class Bean2Map {
 @SuppressWarnings("unchecked")
 public static void main(String[] args) {
 Author author = new Author();
 author.setName("wenliang.li");
 Book book = new Book();
 book.setName("pro spring");
 book.setAuthor(author);
 // 获得book中的一切可读特点,返回到map中
 Map String, Book bookMap = null;
 Map String, Author authorMap = null;
 try {
 bookMap = PropertyUtils.describe(book);
 // Book类中包括一个Author类型的特点
 // 取bookMap中的author bean,并将其一切可读特点返回到authorMap中
 authorMap = PropertyUtils.describe(bookMap.get("author"));
 } catch (IllegalAccessException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 } catch (InvocationTargetException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 } catch (NoSuchMethodException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 // 输出
 // Book Name: pro spring
 // Author Name: wenliang.li
 System.out.println("Book Name: " + bookMap.get("name"));
 System.out.println("Author Name: " + authorMap.get("name"));
}
版权声明
本文来源于网络,版权归原作者所有,其内容与观点不代表超凡娱乐立场。转载文章仅为传播更有价值的信息,如采编人员采编有误或者版权原因,请与我们联系,我们核实后立即修改或删除。

猜您喜欢的文章