1

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

3
  • 5 lines doesn't seem that wordy... Commented Apr 4, 2011 at 1:20
  • Unless you're looking at DI frameworks like Spring or Weld, I don't think there's a better way to do this. Constructors are specific to the implementing class, and cannot be generalized via interfaces. If you don't like this pattern, might I suggest you create a "newInstance" method that returns the abstract type. That would bring subclasses into an interface contract for instantiation. Commented Apr 4, 2011 at 1:23
  • @bdares - he's left out the exception handling ... Commented Apr 4, 2011 at 1:27

2 Answers 2

4

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

I would probably write

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.