[英]How can I create an instance of type dynamically in Java
In my Java application I have method 在我的Java应用程序中,我有方法
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 在此方法的内部,我需要创建对象T的实例,该实例扩展了Transaction
Is it correct to do it in this way 这样做是否正确
T newTransaction = (T) transaction.getClass().newInstance();
I think you should use a factory-interface of type T, that way you can force a create-instance interface on the method-user. 我认为您应该使用类型T的工厂接口,这样就可以在method-user上强制创建实例接口。
public <T extends Transaction> boolean appendTransaction(
T transaction,
Factory<T> factory) {
...
T newTransaction = factory.createTransaction();
...
}
More or less, except that Class.newInstance
is evil: 或多或少,除了Class.newInstance
是邪恶的:
Note that this method propagates any exception thrown by the nullary constructor, including a checked exception. 请注意,此方法传播由nullary构造函数引发的任何异常,包括已检查的异常。 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
. 改用transaction.getClass().getConstructor().newInstance()
,它使用InvocationTargetException
包装在构造函数中引发的异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.