JPC
JPC

Reputation: 8276

Instantiating object of same class from within class in java

I have an abstract class that has a shared method which creates a new instance of that class. I don't want to make a new instance of the actual abstract class (you can't do that anyway) but of the implementing subclass.

In order to do it I'm doing this:

constructor = this.getClass().getConstructor(String.class,String.class);
                    Object[] params = new Object[2];
                    params[0] = "one";
                    params[1]= "two";

                    Object piece = constructor.newInstance(params);

Is there a less wordy way to do this

Upvotes: 1

Views: 3914

Answers (2)

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81674

I would probably write

constructor = this.getClass().getConstructor(String.class,String.class);
Object piece = constructor.newInstance(new String[] {"one", "two"});

Upvotes: 2

WhiteFang34
WhiteFang34

Reputation: 72039

While you could write what you're doing with a little less code, I think there's probably a cleaner way you should consider. You could make an abstract method that extending classes have to implement to construct a new instance. That'll guarantee there's always a safe constructor to call and no instantiation exceptions to deal with either. It'd look something like this for your case:

public abstract class AbstractClass {
    protected abstract AbstractClass newInstance(String str1, String str2);

    public void foo() {
        Object piece = newInstance("one", "two");
    }
}

public class MyClass extends AbstractClass {
    protected AbstractClass newInstance(String str1, String str2) {
        return new MyClass(str1, str2);
    }
}

Upvotes: 4

Related Questions