开发者

How to perform meaningful comparison between two object which do not implement equals method?

开发者 https://www.devze.com 2023-03-31 10:58 出处:网络
I am writing a test cases where I need to me开发者_StackOverflow社区aningful compare two objects which do not implement equals. I don\'t want to write equals or hashcode methods for these objects.

I am writing a test cases where I need to me开发者_StackOverflow社区aningful compare two objects which do not implement equals. I don't want to write equals or hashcode methods for these objects.

Is there an API which can do this for me?


Apache commons-lang has an automatic equals builder - e.g. "reflection-equals". API documentation for EqualsBilder. Also note that there is a HashCodeBuilder in the same library.


Example using this library:

static class A {
    private int a;
    private String b;
    A(int a, String b) {
        this.a = a;
        this.b = b;
    }
}

public static void main(String[] args) {
    A a1 = new A(123, "Hello World!");
    A a2 = new A(321, "Hello!");
    A a3 = new A(123, "Hello World!");

    System.out.println(EqualsBuilder.reflectionEquals(a1, a2, true));
    System.out.println(EqualsBuilder.reflectionEquals(a1, a3, true));
}

Output:

false
true


If it's just for test code you could just create a helper method to encapsulate your assertions:

public static void assertMyClassEquals(MyClass expected, MyClass actual) {
    assertEquals(expected.foo, actual.foo);
    //...
}

But I'm not sure I understand your aversion to creating an equals() method which could obviously be useful.


Sometimes comparing the result of toString is a meaningful comparison.


Yes there is look up the use of a comparator which should suit your needs perfectly.

A link to the JAVA API Interface Comparator

And a link to a blog post explaining how to use it. Comparable and Comparator interfaces-Part 2

0

精彩评论

暂无评论...
验证码 换一张
取 消