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();
+2
source to share
2 answers
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
.
+2
source to share