BeanUtils簡單使用
BeanUtils是apache提供的的一個工具類,在很多地方我們都要用到這個類。下面說說這個類的簡單用法。
相關的使用細節已經在代碼的注釋中說明了。
@Test public void test5(){ try { Person p = new Person(new Book()); //使用beanUtils給對象的屬性賦值 BeanUtils.setProperty(p, "username", "張三"); //使用beanUtils獲取對象的屬性值 System.out.println(BeanUtils.getProperty(p, "username")); //beanUtils支持屬性鏈賦值與獲得值,不過賦值前book要先實例化 BeanUtils.setProperty(p, "book.name", "歷史小說"); System.out.println(BeanUtils.getProperty(p, "book.name")); System.out.println(p.getBook().getName()); //把一個對象的值賦給另一個對象 Person p2 = new Person(); BeanUtils.copyProperties(p2, p); System.out.println(p2.getUsername()+","+p2.getBook().getName()); Map<String,String> map = new HashMap<String, String>(); //把Map的值拷貝給一個JavaBean Person p3 = new Person(); map.put("username", "張三"); map.put("password", "9999"); BeanUtils.populate(p3, map ); System.out.println(p3.getUsername()+","+p3.getPassword()); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { e.printStackTrace(); } }
Person.java
public class Person {private String username; private String password; private int money; private Book book; public Person() { } public Person(Book book) { this.book = book; } public Book getBook() { return book; } public void setBook(Book book) { this.book = book; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getMoney() { return money; } public void setMoney(int money) { this.money = money; }
}</pre>
Book.javapublic class Book {private int id; private String name; private int price; private String author; private Detail detail; private Attribute attribute; public Attribute getAttribute() { return attribute; } public void setAttribute(Attribute attribute) { this.attribute = attribute; } public Detail getDetail() { return detail; } public void setDetail(Detail detail) { this.detail = detail; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; }
}</pre>
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!