0

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).

joelproko
  • 89
  • 7
  • You can create an utility class with methods for converting from one class to the other. Is there any relation between the two classes? – Slimu Sep 05 '16 at 11:34
  • Do you actually really need that conversion? I could imagine using composition to mimic the HashMap interface by providing a View on the underlying HashMap structure ... – Fildor Sep 05 '16 at 11:39
  • @Fildor The main purpose of that conversion would be to free up memory for later stages of the program. Integer keys, for example, take up significantly less memory than string keys. After the conversion, the old object would get garbage-collected, freeing up working memory for the intensive main part of the program. – joelproko Sep 09 '16 at 13:23

1 Answers1

1

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?

Kayaman
  • 72,141
  • 5
  • 83
  • 121