所以我有一个看起来像这样的函数:
public void addExceptionCommands(Class<? extends Throwable> exClass, Command... commands) {
for (Command command : commands) {
try {
//Push the command to the stack of executed commands
executedCommands.push(command);
command.execute();
} catch (CouldNotExecuteCommandException e) {
// Default strategy is to rollback
rollback();
// Log
e.printStackTrace();
//I want to throw exClass here
}
}
}
我想抛出exClass,如何实现?抛出exClass不起作用
编辑:谢谢大家的所有回答,我最终使用了供应商:D
您只能抛出Throwable
和Class
isnt的子类。
但是,您可以修改方法以接受供应商,该供应商会生成新的Throwable,然后可以将其抛出:
public <T extends Throwable> void addExceptionCommands(Supplier<T> exceptionSupplier, Command... commands) throws T {
for (Command command : commands) {
try {
//Push the command to the stack of executed commands
executedCommands.push(command);
command.execute();
} catch (CouldNotExecuteCommandException e) {
// Default strategy is to rollback
rollback();
// Log
e.printStackTrace();
//I want to throw exClass here
final T exception = exceptionSupplier.get();
exception.addSuppressed(e);
throw exception;
}
}
}
然后您可以像这样调用您的方法:
addExceptionCommands(YourException::new, command1, command2, ...);
[当您拥有课程类型时,您可以执行类似的操作
throw exClass.newInstance();
参数是异常的类型。如果您抛出某些东西,它必须是异常的instance。
我认为这不会像您想的那样起作用。
Java的java.util.concurrent包提供了一种替代方法。考虑ExecutorService.submit()
方法和Future.get()
方法。提交给执行者的任务会引发各种各样的异常。但是Future.get()
将抛出的所有异常包装在一个定义明确并声明为Future.get()
的状态。
尝试使用ExecutableException
[java.lang.reflect.Constructor
优于Constructor.newInstance()
,因为它允许您使用参数来创建新实例。
Class.newInstance()
带有Constructor constructor = exClass.getDeclaredConstructor();
Throwable ex = (Throwable) constructor.newInstance();
throw ex;
参数(用于消息?)
String
Constructor constructor = exClass.getDeclaredConstructor(String.class);
Throwable ex = (Throwable) constructor.newInstance("message goes here");
throw ex;
此外,https://docs.oracle.com/javase/tutorial/reflect/member/ctorInstance.html已被弃用。Class.newInstance()