If you hava a lot of objects then instead of adding toString
in every class use code instrumentation (you can alter .class in jars or change them at loadtime using javaagent). For example AspectJ would help, but there are lots other alternatives. For example you can do such a thing (using AspectJ and ToStringBuilder from Apache Commons):
@Aspect
public class ToStringAspect {
@Around("execution(String *.toString()) && target(t) && within(your.target.package.*)")
public String toStringCall(Object t) {
return ToStringBuilder.reflectionToString(t);
}
}
ToStringBuilder is very flexible. e.g. if you don't need class name use style by setting StandardToStringStyle#setUseClassName(false):
public String toStringCall(Object t) {
StandardToStringStyle style = new StandardToStringStyle();
style.setUseClassName(false);
style.setUseIdentityHashCode(false);
ToStringBuilder builder = new ReflectionToStringBuilder(t, style);
return builder.toString();
}