将 child 投射到 parent 到其他 child

cast child to parent to other child

我有两个非常相似的 类(它们共享许多变量),我想将一个转换为另一个。简化成这样:

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 */
}

因为我想避免手动复制每个共享变量,所以我想出了这个主意:

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 */
    }
}

但显然那是行不通的。有办法吗?我的主要目标是避免不得不做这样的事情:

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);
}

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;
}

ClassForJacksonDatabind 的结构是从外部 JSON 文件导出的,所以我无法更改它(据我所知,无论如何)。

有很多对象到对象映射的库,例如Dozer。您真的想重新发明轮子并创建自己的映射器吗?