把孩子交给其他孩子的父母

时间:2016-09-05 11:29:59

标签: java casting coercion

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

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文件派生的,所以我无法改变它(据我所知,无论如何)。

1 个答案:

答案 0 :(得分:1)

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