所以我有一个看起来像这样的函数:
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不起作用
编辑:
谢谢大家的所有回答,我最终使用了Supplier:D
最佳答案
您只能抛出Throwable
和Class
isnt的子类。
但是,您可以修改方法以接受生成新Throwable的供应商,然后可以抛出该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, ...);
关于java - throw 类<?扩展Throwable>,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58959238/