users@jaxb.java.net

Re: toString() methods on generated classes

From: Kohsuke Kawaguchi <Kohsuke.Kawaguchi_at_Sun.COM>
Date: Thu, 14 Sep 2006 11:24:51 -0700

Hanson Char wrote:
> I've got a simple/dumb toString generation (using Jakarta commons) working.

Nice. Feel free to update http://jaxb2-commons.dev.java.net/ --- you
have a commit access, right?

> 1) How can I add more package imports to the beginning of the generated
> class, so I don't need to refer to the fully qualified class names in the
> methods ?

If you use CodeModel's methods to generate expressions, CodeModel will
take care of the formatting and import declarations.

If you use The "direct" method to inject String as a code fragment,
CodeModel can't figure out what classes are used there, so it can't help.

We can't really just let you "add package imports to the beginning of
the generated class", because until we complete the generation of a
while compilation unit, we can't really determine what classes can be
imported and what cannot. For example, believe it or not there are
schemas out there that defines a "String" type. CodeModel is written
carefully to handle such extreme situations correctly.

So for example, if you generate a body in a method, you'd do:

   JMethod m = clazz.method(....);
   m.body()._return(JExpr.lit(true));

or things like that. Check XJC for how it's doing various code
generation, and I think you'll get the idea.



> 2) Is it common practice to pass additional config info to running the xjc
> plugin, so it can, say, generate toString using different ToStringStyle, or
> whether a toXml() should be generated or not, etc. ? If so, is System
> properties to way to go, or there is a better way ?

A better way to go is either to use additional command-line options (you
can define as many as you like by simply recognizing them in your
parseArgument method.)

Another approach is to take argument to your primary option that you
return from Plugin.getOptionName(). Starting from 2.1, when the user
specifies an option that matches getOptionName(), XJC will then invoke
your parseArgument() option, so that you can claim additional arguments
that follow the option. This is 2.1 only, though.


> If it's not too much overhead to handle multiple small projects, I'd
>> actually suggest you create a different source tree and etc. But that's
>> up to you.
>
> What would be some good names for these small projects ? Any suggestion ?

say, commons-lang-toString plugin and/or xstream-toXml plugin?

> Can you create the tree roots so I can check stuff in, or do I have the
> permission to do so ?

I'm happy to create ones for you, but you should also have a full commit
access to jaxb2-commons.

-- 
Kohsuke Kawaguchi
Sun Microsystems                   kohsuke.kawaguchi_at_sun.com