public String toString() {
return getClass().getName()+"@"+Integer.toHexString(hashCode());
}
public class Car {
private String model;
private String color;
// здесь стандартные геттеры и сеттеры. Нет реализации метода toString()
}
com.test.tostring.Car@6d06d54c
public class CarPrimitiveToString extends Car {
private long weight;
@Override
public String toString() {
return "Car [weight=" + weight + ", getModel()=" + getModel()
+ ", getColor()=" + getColor() + "]";
}
}
@Test
public void givenPrimitive_whenToString_thenCarDetails() {
CarPrimitiveToString car = new CarPrimitiveToString();
car.setModel("Ford");
car.setColor("White");
car.setWeight(1300);
assertEquals("Car [weight=1300, getModel()=Ford, getColor()=White]",
car.toString());
}
public class CarComplexObjectToString extends Car {
private Order order;
//здесь стандартные геттеры и сеттеры
@Override
public String toString() {
return "Car [order=" + order + ", getModel()=" + getModel()
+ ", getColor()=" + getColor() + "]";
}
}
public class Order {
private String orderId;
private String desc;
@Override
public String toString() {
return "Order [orderId=" + orderId + ", desc=" + desc + "]";
}
}
@Test
public void givenComplex_whenToString_thenCarDetails() {
CarComplexObjectToString car = new CarComplexObjectToString();
// .. здесь заполняем car
Order order = new Order();
order.setOrderId("4512");
order.setDesc("car order");
car.setOrders(order);
assertEquals("Car [order=Order [orderId=4512, desc=car order], " +
"getModel()=Ford, getColor()=White]", car.toString());
}
public class CarArrayToString extends Car {
private Order[] orders;
@Override
public String toString() {
return "Car [orders=" + Arrays.toString(orders)
+ ", getModel()=" + getModel()
+ ", getWhite()=" + getWhite() + "]";
}
}
@Test
public void givenArray_whenToString_thenCarDetails() {
CarArrayToString car = new CarArrayToString();
// .. здесь заполняем car и order
car.setOrders(new Order[] { order });
assertEquals("Car [orders=[Order [orderId=4512, desc=car order]], " +
"getModel()=Ford, getColor()=White]", car.toString());
}
public class CarWrapperCollectionToString extends Car {
private Integer year; // Wrapper class
private List<String> orders; // Collection
private StringBuffer pilot; // StringBuffer
@Override
public String toString() {
return "Car [year=" + year + ", orders=" + orders + ", pilot=" + pilot
+ ", getModel()=" + getModel() + ", getColor()=" + getColor() + "]";
}
}