[Groovy] @Canonical annotation - @EqualsAndHashCode, @ToString, @TupleConstructor

by 스뎅(thDeng) on

@Canonical annotation은 하나로 간단하게 3개 annotation을 모두 넣은 것과 같다.

간단하게 각 annotation을 붙인 샘플 코드로 확인..

class Person {
	String lastName
	String firstName
}

@groovy.transform.EqualsAndHashCode
class EqualsAndHashCodePerson {
	String lastName
	String firstName
}

@groovy.transform.ToString
class ToStringPerson {
	String lastName
	String firstName
}

@groovy.transform.TupleConstructor
class TupleConstructorPerson {
	String lastName
	String firstName
}

@groovy.transform.Canonical
class CanonicalPerson {
	String lastName
	String firstName
}

Person p1 = new Person(lastName: "last", firstName: "first")
Person p2 = new Person(lastName: "last", firstName: "first")
assert p1 != p2

EqualsAndHashCodePerson ep1 = new EqualsAndHashCodePerson(lastName: "last", firstName: "first")
EqualsAndHashCodePerson ep2 = new EqualsAndHashCodePerson(lastName: "last", firstName: "first")
assert ep1 == ep2 // equals

ToStringPerson tp1 = new ToStringPerson(lastName: "last", firstName: "first")
assert tp1.toString() == "ToStringPerson(last, first)" // toString

TupleConstructorPerson tup = new TupleConstructorPerson("last", "first") // tuple constructor
assert tup.lastName == "last"
assert tup.firstName == "first"

CanonicalPerson cp1 = new CanonicalPerson("last", "first") // tuple constructor
CanonicalPerson cp2 = new CanonicalPerson("last", "first")
assert cp1 == cp2 // equals
assert cp1.toString() == "CanonicalPerson(last, first)" // toString

참고

별도로 명시하지 않을 경우, 이 블로그의 포스트는 다음 라이선스에 따라 사용할 수 있습니다: Creative Commons License CC Attribution-NonCommercial-ShareAlike 4.0 International License