
- 官網下載: http://commons.apache.org/proper/commons-lang/
- commons-lang-2.6.jar導入到專案中。
- 或使用 Maven Reponsitory,選擇版本後,在 pom.xml貼上:
<dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> </dependency>

Mix加上@Override註解,確定正確地覆寫equals(),用instanceof判斷是否為相同物件,然後用EqualsBuilder來比較兩個物件的field值,因為Mix的商務邏輯是id,它是唯一值,所以用getId()取值,對id作比較,最後記得呼叫isEquals()取傳回值。
package org.openyu.java.commons.lang; import org.apache.commons.lang.builder.EqualsBuilder; /** * The Class Book. */ public class Book { /** The id. */ private long id; /** The name. */ private String name; /** * The Constructor. */ public Book() { } /** * Gets the id. * * @return the id */ public long getId() { return id; } /** * Sets the id. * * @param id * the id */ public void setId(long id) { this.id = id; } /** * Gets the name. * * @return the name */ public String getName() { return name; } /** * Sets the name. * * @param name * the name */ public void setName(String name) { this.name = name; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (!(obj instanceof Book)) { return false; } Book other = (Book) obj; return new EqualsBuilder() .append(getId(), other.getId()) .isEquals(); } }
Mix撰寫一些測試程式碼,來檢查看看,是否符合預期,book需與book2相等。
package org.openyu.java.commons.lang; import static org.junit.Assert.*; import org.junit.Test; /** * The Class BookTest. */ public class BookTest { /** * Equals. */ @Test public void equals() { Book book = new Book(); book.setId(1); // Book book2 = new Book(); book2.setId(1); // boolean result = book.equals(book2); System.out.println("book.equals(book2) = " + result); assertTrue(result); } }
測試成功了,符合了Mix的預期。
console查看其結果。
book.equals(book2) = true
沒有留言:
張貼留言