users@jaxb.java.net

Re: fluent-api plugin - generic return types

From: Hanson Char <hanson.char_at_gmail.com>
Date: Thu, 12 Oct 2006 08:54:15 -0700

Hi Kenny,

Is Y a Jaxb generated pojo ? Or a hand coded one ?

How about the alternative of using method overriding with covariant
return type in Y ? Example:

class Y extends X {
    public Y withA(String a) {
       setA(a);
       return this;
    }
}

Hanson

On 10/12/06, Kenny MacLeod <kenny.macleod_at_kizoom.com> wrote:
>
>
>
> Hi Hanson,
>
> I've been trying to use the fluent-api JAXB2 plugin with a schema which
> makes heavy use of type inheritence. The problem here is that the return
> types of the withXYZ() methods are not inheritence friendly.
>
> Let me give an example. Say XJC generates two classes, X and Y, where Y
> extends X.
>
> class X {
> private String a;
>
> public String getA() { return a; }
> public void setA(String a) { this.a = a; }
>
> public X withA(String a) {
> setA(a);
> return this;
> }
> }
>
> class Y extends X {
>
> }
>
>
> Now take some client code:
>
> Y y = new Y().withA("value");
>
> Logically, you'd want this to work, but because withA() returns type X, it
> can't be assigned to y.
>
> I was thinking that the return type of withA() could be altered to use java5
> generics, something like this:
>
> public <T extends X> T withA(String a) {
> setA(a);
> return (T) this;
> }
>
> This should allow the result of withA() to be assigned to any variable of
> type Y without casting or compilation warnings. It does get a bit
> confusing, though, when you start chaining them together, with some withers
> in X and some in Y.
>
> That's my proposal, anyway. I think the plugin codemodel can produce
> generic return types, I just don't know how (the codemodel API makes my
> brain hurt).
>
> kenny
>
>
>