【问题标题】:cast child to parent to other child将孩子投给父母给其他孩子
【发布时间】:2016-09-05 11:29:58
【问题描述】:

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

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 文件,因此我无法更改它(据我所知,无论如何)。

【问题讨论】:

  • 您可以创建一个实用程序类,其中包含从一个类转换为另一个类的方法。这两个类之间有什么关系吗?
  • 您真的需要这种转换吗?我可以想象通过在底层 HashMap 结构上提供 View 来使用组合来模仿 HashMap 接口...
  • @Fildor 该转换的主要目的是为程序的后期阶段释放内存。例如,整数键比字符串键占用的内存要少得多。转换后,旧对象将被垃圾回收,为程序的密集主要部分释放工作内存。

标签: java casting coercion


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-03
    • 2020-07-22
    • 2020-05-26
    • 1970-01-01
    • 1970-01-01
    • 2013-06-04
    • 2012-08-29
    • 1970-01-01
    相关资源
    最近更新 更多