2

In my Java application I have method

public <T extends Transaction> boolean appendTransaction(T transaction) {
   ...
}

and inside of this method I need to create an instance of object T which extends Transaction

Is it correct to do it in this way

T newTransaction = (T) transaction.getClass().newInstance();

2 Answers 2

5

I think you should use a factory-interface of type T, that way you can force a create-instance interface on the method-user.

public <T extends Transaction> boolean appendTransaction(
        T transaction, 
        Factory<T> factory) {
    ...
    T newTransaction = factory.createTransaction();
    ...
}
1
  • I sorta agree with you here. It's definitely cleaner and less magical.
    – gustafc
    Oct 9, 2009 at 8:53
2

More or less, except that Class.newInstance is evil:

Note that this method propagates any exception thrown by the nullary constructor, including a checked exception. Use of this method effectively bypasses the compile-time exception checking that would otherwise be performed by the compiler.

Use transaction.getClass().getConstructor().newInstance() instead, it wraps exceptions thrown in the constructor with an InvocationTargetException.

2
  • Is more evil then just an alias for getConstructor().newInstance() ? Oct 9, 2009 at 8:41
  • I updated with a motivation. It magically rethrows any exceptions thrown by the default constructor, even checked exceptions which you then can't catch explicitly (because Class.newInstance doesn't declare them in its signature).
    – gustafc
    Oct 9, 2009 at 8:43

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.