views:

145

answers:

2

Hello.

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  A: 

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.

gustafc
Is more evil then just an alias for getConstructor().newInstance() ?
Bogdan Gusiev
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
+4  A: 

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();
    ...
}
crunchdog
I sorta agree with you here. It's definitely cleaner and less magical.
gustafc