users@jaxb.java.net

Re: jaxb2 and toString generation

From: Aleksei Valikov <valikov_at_gmx.net>
Date: Sat, 12 Mar 2011 12:04:40 +0100

Hi,

> I am experimenting with JAXB2 Basics toString method.
>
> I cannot get a toString method generated from my .xsd file automatically.
>
> Below is my .xsd file, for reference.
>
> I can however, inject code, as you can see from the .xsd file.
>
> Documentation on this subject…. Well, I cannot find it on the net.
>
> The Purchase Order Example does not seem to refer to any toString or
> Hashcode generation at all.
>
> I wonder if you could clarify some problems  I run into.
>
> 1: Can a toString method, returning the value of “description” be generated
> at all, by adjusting ONLY the .xsd file?

Yes, you can accomplish this by excluding the "unwanted" properties,
check the "Excluding properties" section here:

http://confluence.highsource.org/display/J2B/JAXB2+Basics+Plugins

> 2:  I can get a toString method generated, that looks like this:
>
>         public String toString() {
>
>             final ToStringStrategy strategy = JAXBToStringStrategy.INSTANCE;
>
>             final StringBuilder buffer = new StringBuilder();
>
>             append(null, buffer, strategy);
>
>             return buffer.toString();
>
>         }
>
> , by doing nothing much special in the .xsd file, only using –XtoString on
> xjc’s commandline.
>
> But how is that going to return the value of “description”?

ToString plugin generates toString() methods which create string
representation of the object based on it's properties. It's not about
"custom" toString implementation, it's about "automatic". So it's
inherently not designed to be able to customize "this is how I want my
toString".

The plugin allows you to ignore some of the properties, so you can
actually achieve "description" only, but you can't tune it much more
than this.

Another option is to use strategies to implement your own toString
generation, see below.

> 3: What exactly is  a JAXBToStringStrategy class and what would it look
> like, to give me the value of “description”?

See the ToStringStrategy interface. It is implements the string
creation algorithm. You can implement your own strategy and override
string creation depending on type or location of the item.

For instance, theoretically you could subclass JAXBToStringStrategy
and do something like:

@Override
protected StringBuilder appendInternal(ObjectLocator locator,
                        StringBuilder buffer, Object value)
{
   if (value instanceOf MySpecialType)
   {
     // Create toString for your special type
   }
   else { // super }
}

But, once again, the plugin focuses on automatic toString creation
according to one strategy applied for all the generated classes
(unless you exclude something). It's not about tuning how exactly
toString should look like for each individual class.

Bye,
/lexi