I want to have all of my classes implement toString() the same way using Java reflection. There are two ways I came up with.
-
Create a base class such as
MyObjectoverridingtoString()and all my classes would extend it, but I’m not sure if it’d be an overkill. -
Use Eclipse to generate the overridden
toString()for each class. The downside of it is that there’d be a lot of code redundancy.
Which is the preferred method? If you go with Eclipse templates, is there a way to auto-generate it when you do New > Class, instead of having to do Source > Generate toString() every time?
As Harkness says, use commons-lang ReflectionToStringBuilder.
Rather than have a base class, I’d use AOP such as aspectj to inject this implementation into all of your classes at compile time.
Another option is to use a tool like ASM to transform your classes at compile time to inject toString methods. Both approaches use the same basic concepts, ASM being a more ‘raw’ version of class file modification.