开发者

In Java How do I create a new class of the same type as 'this' class? Java

I have a simple scenario. I'd like to create a new instance of the class below.

class A implements Fancy {
    void my() {
        Fancy b = // new X(); where X could be A or B
    }
}开发者_如何学Python

When you have a B which implements Fancy as well.


Create an abstract class AbstractFancy with a create method:

abstract class AbstractFancy implements Fancy {
    abstract Fancy create();

    void my() {
        Fancy b = create();
        //....
    }
}

In each class implement the create method:

class A extends AbstractFancy {
    Fancy create() {
        return new A();
    }
}
class B extends AbstractFancy {
    Fancy create() {
        return new B();
    }
}


I'm assuming you want my() to be defined in a base class, like a FancyAdapter, which has different child classes, and you want it to create an instance of the actual concrete child class. If you can assume that all classes implementing Fancy have a default (no-argument) constructor:

Fancy b = (Fancy) getClass().newInstance();


class A implements Fancy {
    void my() {
        Fancy b = (Fancy)getClass().newInstance();
    }
}


Reflectively? (not recommended)

Fancy b = this.getClass().newInstance();

This will work if there is a zero-argument based constructor (implicit or explicit). Make sure you do a try {} catch{} around the statement.

Other way:

class A implements Fancy, Cloneable {

    void my() {
        try {
            Fancy b = (Fancy) clone();
        } catch (CloneNotSupportedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Alternatively, you would want a Builder that creates a new Fancy object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜