Write toString () once and for all?

I want all my classes to implement toString() in the same way using Java reflection. There are two ways that I came with.

  • Create a base class like MyObject overriding toString() and all my classes will extend it, but I'm not sure if this will be excessive.

  • Use Eclipse to generate an overridden toString() for each class. The disadvantage of this is that there will be a lot of code redundancy.

What is the preferred method? If you come with Eclipse templates, is there a way to automatically generate it when you do New> Class, instead of doing Source> Generate toString () each time?

+6
source share
4 answers

As Harknes says, use commons-lang ReflectionToStringBuilder.

Instead of a base class, I would use AOP, such as aspectj , to inject this implementation into all your classes at compile time.

Another option is to use a tool like ASM to convert your classes at compile time to introduce toString methods. Both approaches use the same basic concepts, ASM is a more "raw" version of a class file modification.

+5
source

See ToStringBuilder and its subclass ReflectionToStringBuilder from Apache Commons Lang . The latter allows you to fully implement toString() in the base class or add it to the template:

 public String toString() { return ReflectionToStringBuilder.toString(this); } 
+3
source

Option 1 is a really bad idea because it imposes a β€œis” constraint on your implementations without a good reason, and each of your classes should inherit from the same base class. This is hardly possible.

Option 2 is also a bad idea - you will have the same code that repeats in each class - a service nightmare and does not add value.

The best option is to use a utility class:

 public class MyUtils { public static String toString(Object object) { // your reflection impl here } } public class MyClass { ... public String toString() { return MyUtils.toString(this); } } 
+3
source

You can also use lombok for this:

http://www.projectlombok.org/features/ToString.html

If you are interested in additionally generating all getters, setters, toString, hashCode and equal, you can use the @Data annotation, see

http://www.projectlombok.org/features/Data.html

+2
source

Source: https://habr.com/ru/post/899503/


All Articles