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

1 Comment

I sorta agree with you here. It's definitely cleaner and less magical.
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 Comments

Is more evil then just an alias for getConstructor().newInstance() ?
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).

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.