joelproko
joelproko

Reputation: 89

cast child to parent to other child

I have two very similar classes (they share many variables) and I want to convert one into the other. Simplified like this:

class ClassForJacksonDatabind
{
    public boolean a;
    public int     b;
    /* ... */
    public float     z;
    /* ... */
    public HashMap<String,Double> different;
}
class Preferred
{
    protected boolean a;
    protected int     b;
    /* ... */
    protected float     z;
    /* ... */
    protected HashMap<Integer,Double> different;
    /* getters and setters */
}

Because I'd like to avoid manually copying every single shared variable, I came up with this idea:

abstract class AbstractPreferred
{
    public boolean a;
    public int     b;
    /* ... */
    public float     z;
    /* ... */
    /* getters and setters */
}
class ClassForJacksonDatabind extends AbstractPreferred
{
    public HashMap<String,Double> different;
    /* getter and setter for different */
    public Preferred toPreferred()
    {
        Preferred p = (AbstractPreferred) this;
        p->convertDifferent(this.different);
        return p;
    }
}
class Preferred extends AbstractPreferred
{
    protected HashMap<Integer,Double> different;
    /* getters and setters */
    public void convertDifferent(HashMap<String,Double> d)
    {
        /* conversion */
    }
}

But obviously that doesn't work. Is there a way it could? My main aim is avoiding to have to do something like this:

public Preferred toPreferred()
{
    Preferred p = new Preffered();
    p.setA(this.a);
    p.setB(this.b);
    /* ... */
    p.setZ(this.z);
    p.setAa(this.aa);
    /* ... */
    p.setZz(this.zz);
    p.convertDifferent(this.different);
}

or

public Preferred toPreferred()
{
    Preferred p = new Preferred(this);
    p.convertDifferent(this.different);
}
/* ... */
Preferred(AbstractPreferred other)
{
    this.a = other.a;
    this.b = other.b;
    /* ... */
    this.zz = other.zz;
}

The structure of ClassForJacksonDatabind is derived from an external JSON file, so I cannot change it (as far as I know, anyway).

Upvotes: 0

Views: 268

Answers (1)

Kayaman
Kayaman

Reputation: 73548

There are plenty of libraries for Object to Object mapping, such as Dozer. Do you really want to reinvent the wheel and create your own mapper?

Upvotes: 1

Related Questions