Java – write toString () once and for all?

I want all my classes to implement toString () in the same way using java reflection I came up with two ways

>Create a base class, such as MyObject that overrides tostring(). All my classes will extend it, but I'm not sure if it's a little too much. > Use eclipse to generate an overridden toString () for each class Its disadvantage is that there is a lot of code redundancy

Which method is preferred? If you use an eclipse template, is there any way to generate it automatically when you execute new >? Class instead of having to do source > every time tostring() is generated?

Solution

As Harkness said, use commons Lang reflectiontostringbuilder

Instead of using base classes, I use AOP such as AspectJ to inject this implementation into all classes at compile time

Another option is to use tools like ASM to convert classes at compile time to inject toString methods Both methods use the same basic concept. ASM is a more "original" version of class file modification

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>