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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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; } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
Book.java
public 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; } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
BeanUtils還有許多好用的方法,想要詳細了解可以查看官方的幫助文檔。
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。