克隆实例化的抽象类 [英] Cloning an instantiated abstract class

查看:102
本文介绍了克隆实例化的抽象类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实例化一个抽象类。 ->复制它,并保留抽象方法的实现。

    public abstract class Foo{… 

    public int myVar;

    public abstract void do();

     }//Foo

包中的其他位置:

public class Gha{ … 

    Foo testFoo = new Foo{

        @Override
        public void do(){
            Log.i("" , "this is a special Foo"); //executable process
        }//do

    }//testFoo
    …
}//Gha

我可以复制 testFoo 的方式复制 testFoo .do()方法主体用于新的 Foo

Can I copy testFoo in a way that copies testFoo’s .do() method body for the new Foo?

推荐答案

您可以使用 clone 。不鼓励使用这种方法,但是确实可以使用。

You could use clone. The use of this method is widely discouraged, but it does work.

例如:

public abstract class Foo implements Cloneable {

    private int a;
    private String b;

    public Foo(int a, String b) {
        this.a = a;
        this.b = b;
    } 

    public abstract void run();

    public int getA() { return a; }

    public String getB() { return b; }

    @Override
    public final Foo clone() {
        try {
            return (Foo) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new AssertionError(); // Can't happen
        }
    }
}

然后,您可以执行以下操作:

Then, you can do:

Foo original = new Foo(3, "bar") {
    @Override
    public void run() {
        System.out.println("Hello, world!");
    }
};
Foo copy = original.clone();
System.out.println(copy.getA());
System.out.println(copy.getB());
copy.run();
System.out.println(copy == original);

输出为:

3
bar
Hello, world!
false

另一种方法是使用 Serializable

public abstract class Foo implements Serializable {

    private int a;
    private String b;

    public Foo(int a, String b) {
        this.a = a;
        this.b = b;
    }

    public abstract void run();

    public int getA() { return a; }

    public String getB() { return b; }

    public final Foo copy() {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            new ObjectOutputStream(baos).writeObject(this);
            return (Foo) new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())).readObject();
        } catch (Exception e) {
            throw new AssertionError(); 
        }
    }
}

使用此版本,替换克隆通过复制,您将得到相同的结果。

With this version, replace clone by copy and you'll get the same result.

这篇关于克隆实例化的抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆