/java/

Guava toString

2014-05-30 00:17:48

    @Test
    public void testToString() {
        assertThat(new Car().toString()).isEqualTo("Car{name=Lorem, desc=Ipsum, number=1}");
    }

    class Car {
        private String name = "Lorem";
        private String desc = "Ipsum";
        private Integer number = 1;

        @Override
        public String toString() {
            return Objects.toStringHelper(this)
                    .add("name", name)
                    .add("desc", desc)
                    .add("number", number)
                    .toString();
        }

        @Override
        public boolean equals(Object o) {
            return Objects.equal(this, o);
        }

        @Override
        public int hashCode() {
            return Objects.hashCode(name, desc, number);
        }
    }

<dependency>
<groupid>com.google.guava</groupid>
<artifactid>guava</artifactid>
<version>17.0</version>
</dependency>