How can I instantiate a type dynamically in Java
In my Java application, I have a method
public <T extends Transaction> boolean appendTransaction(T transaction) {
...
}
and inside this method I need to instantiate an object T that extends Transaction
Is it the right thing to do
T newTransaction = (T) transaction.getClass().newInstance();
I think you should use a factory -interface of type T, this way you can force create-instance on the user of the method.
public <T extends Transaction> boolean appendTransaction(
T transaction,
Factory<T> factory) {
...
T newTransaction = factory.createTransaction();
...
}
More or less, except for what Class.newInstance
is evil:
Note that this method applies to any exception thrown by the nullable constructor, including the checked exception. Using this method effectively bypasses compile-time exception checking that would otherwise be performed by the compiler.
Use transaction.getClass().getConstructor().newInstance()
, it wraps exceptions thrown in the constructor with InvocationTargetException
.