本文介绍了Java:如何复制对象,使其来自同一子类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用一个简单的示例来更好地理解:我有一个类Tool和子类,这些类扩展了类Tool:HammerSaw.两者都定义了某些字段,例如weight,并且都使用自己的实现覆盖了方法getCost.

I try to use a simple example for better undersanding: I've got a class Tool and child classes which are extending class Tool: Hammer, Saw. Both have defined some fields like weight and both are overriding method getCost with own implementation.

    Tool first_tool = new Hammer();
    Tool second_tool = new Saw();

我需要Tool类中的方法,该方法可以复制任何工具,例如,first_tool_copy来自与first_tool相同的子类.我怎样才能做到这一点?我需要类似的东西:

I need a method in Tool class, that will to do a copy of any tool, such way, that first_tool_copy is from the same subclass as first_tool. How can I make this possible? I need something like:

    /* Copy tool, change parameters of copy, the original won't change */
    /* first_tool_copy will be instance of Hammer class */
    first_tool_copy = first_tool.copy
    first_tool_copy.weight = 100

结论:我想为所有子类提供一些简单的复制构造函数.

Conclusions: I would like to have some simple copy constructor common for all subclasses.

推荐答案

我将使Tool抽象,并向Tool添加abstract copy方法.然后,每个子类都必须提供自己的实现.这是一种相当面向对象的方法,并且利用了动态分配的优势.

I would make Tool abstract, and add an abstract copy method to Tool. Then each subclass is forced to provide its own implementation. This is a fairly OO approach, and takes advantage of dynamic dispatch.

abstract class Tool
{
    // snip...
    public abstract Tool copy();
    // snip...
}

class Hammer
{
    // snip...
    public Tool copy()
    {
        Hammer h = new Hammer();
        // copy fields from this to h
        return h;
    }
    // snip...
}

否则,您将在Tool中提供一个具体的实现,您必须每次执行一次更新才能处理Tool的新子类.此方法必须使用instanceofgetClass()或类似的非OO技术来创建正确的类.真是

Otherwise, you'd provide a concrete implementation in Tool which you'd have to update every time to want to handle a new subclass of Tool. This method would have to use instanceof, getClass(), or similar non-OO techniques to create the right class. Ew.

请记住 有效的Java 第10项告诉我们的内容: 明智地覆盖clone.

Remember what Effective Java Item 10 tells us: Override clone judiciously.

假设Tool实现看起来像下面的类,您可以通过反射来做到这一点:

Assuming the Tool implementation looks something like the below class, you could do this with reflection:

class Tool
{
    // ...

    public Tool () {}

    public int getWeight ()
    {
        // don't care about implementation
    }

    public void setWeight()
    {
        // don't care about implementation
    }

    // ignores all exceptions - not production code!
    public Tool copy() throws Exception
    {
        Tool copy = this.getClass().getConstructor().newInstance();
        copy.setWeight(this.getWeight());
        return copy;
    }

    // ...
}

不过,我不建议这样做.对我来说,这很臭而且很丑.

I wouldn't recommend this, though. It's just smelly and ugly to me.

这篇关于Java:如何复制对象,使其来自同一子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 04:46