1

SOF에서 검색했지만 BeanUtil 사용과 관련된 기본적인 질문을 찾지 못했습니다.Apache Common BeanUtil의 BeanComparator를 올바르게 사용하여 인트로 스펙 션의 이점을 얻는 방법은 무엇입니까?

public class UserPojo{ 

    private String name; 
    private int gender; 
    private int size; 

    //Setters 
    public void setName(String name) {this.name =name;} 
    public void setGender(int gender){this.gender=gender;} 
    public void setSize(int size) {this.size =size;} 

    //getters 
    public String getName() {return this.name;} 
    public int getGender(){return this.gender;} 
    public int getSize() {return this.size;} 
} 

내 질문은, 어떻게 자동으로 빈의 두 인스턴스를 비교하는 BeanUtil을 사용하는 것입니다 :

나는 POJO 클래스의 누구 클래스 코드 예를 UserPojo에 대한 말을 할 수 있나요?

나는이 시도 :

final BeanComparator<UserPojo> comparator = new BeanComparator<UserPojo>(); 
final int comparison = comparator.compare(expectedPojo, receivedPojo); 

을하지만, 다음과 같은 오류에 끝 :

java.lang.ClassCastException : UserPojo cannot be cast to java.lang.Comparable 

내가, 내 뽀조 표준 Comparable 인터페이스를 구현해야 이해하지만 이런 식의 비교는 의존하지 않는 인트로 스펙 션과 BeanUtil의 임포트는 매우 쓸모없는 것처럼 보입니다 ...

그래서 올바르게 사용하는 방법은 무엇입니까?

답변

0

당신은 거기에 다양한 생성자에서 꼭보고했습니다 :

여기의 이전의 javadoc의 (2 차 파라가 답이다) :

this(null); 

비교 :

Constructs a property-based comparator for beans. This compares two beans by the property specified in the property parameter. This constructor creates a BeanComparator that uses a ComparableComparator to compare the property values.

Passing "null" to this constructor will cause the BeanComparator to compare objects based on natural order, that is java.lang.Comparable.

예상대로, 당신이 호출하고있는 생성자는이 수행 여러 속성을 사용하면 두 번째 변형을 사용할 수 있습니다.

Collections.sort(collection, 
    new BeanComparator("property1", 
    new BeanComparator("property2", 
     new BeanComparator("property3")))); 

나는 개인적으로 더 나은 선택으로 Apache Commons CompareToBuilderGoogle Guava’s ComparisonChain을 느꼈다.

+0

는'compareToBuilde' 및 몰라'comparisonChain'들이 자동적 인 콩 comprarison이 가능합니까? –

+0

아니요,하지만'compareTo' 메소드를 구현하는 데 도움이됩니다. 단지'EqualsBuilder'가'equals' 메소드를 만드는 데 도움이됩니다. 가장 큰 장점은 아니지만 'BeanComparator'에서 매개 변수 이름을 지정해야 할 필요가 있습니다. (아마도 b/c를 사용합니다.) BeanComparator에서 나와 잘 맞지 않습니다. – mystarrocks

0

마침내 이것을 포기하고 코드를 작성했습니다. 이 질문에 대답하지 않지만이이 문제를 해결하기 위해 나의 방법입니다

import org.apache.commons.beanutils.BeanUtils; 

public static void assertBeansEqual(final Object expected, final Object given) { 
    try { 
     final Map<String, String> expectedDescription = BeanUtils.describe(expected); 
     final Map<String, String> givenDescription = BeanUtils.describe(given); 

     // if the two bean don't share the same attributes. 
     if (!(expectedDescription.keySet().containsAll(givenDescription.keySet()))) { 
      final Set<String> keySet = givenDescription.keySet(); 
      keySet.removeAll(expectedDescription.keySet()); 
      fail("The expected bean has not the same attributes than the given bean, the followings fields are not present in the expected bean :" + keySet); 
     } 
     if (!(givenDescription.keySet().containsAll(expectedDescription.keySet()))) { 
      final Set<String> keySet = expectedDescription.keySet(); 
      keySet.removeAll(givenDescription.keySet()); 
      fail("The expected bean has not the same attributes than the given bean, the followings fields are not present in the given bean :" + keySet); 
     } 

     final List<String> differences = new LinkedList<String>(); 
     for (final String key : expectedDescription.keySet()) { 
      if (isNull(expectedDescription.get(key))) { 
       // if the bean1 value is null and not the other -> not equal. This test is 
       // required to avoid NPE attributes values are null. (null object dot not have 
       // equals method). 
       if (!isNull(givenDescription.get(key))) { 
        differences.add(key); 
       } 
      } 
      else { 
       // if two attributes don't share an attributes value. 
       if (!expectedDescription.get(key).equals(givenDescription.get(key))) { 
        differences.add(key); 
       } 
      } 
     } 
     if (!differences.isEmpty()) { 
      String attributes = ""; 
      for (final String attr : differences) { 
       attributes = attributes + "|" + attr; 
      } 
      fail("Assertion fail, the expected bean and the given bean attributes values differ for the followings attributes : " + attributes + "|"); 
     } 
    } 
    catch (final Exception e) { 
     e.printStackTrace(); 
     fail(e.getMessage()); 
    } 
}