我正在尝试构建一个用于生成 RuntimeExceptions 的工厂方法。
我们的想法是通过执行以下代码片段来抛出异常:
throw ExceptionFactory.build(CustomException.class, CustomException.NOT_FOUND);
构建方法的第一个参数是异常类,但是第二个参数将引用在 CustomException 类中定义的枚举,用于在构建异常时加载其他详细信息。
例子:
public class CustomException extends RuntimeException {
public static final ExceptionType NOT_FOUND = ExceptionType.NOT_FOUND;
//constructors, getters, setters, etc..
private enum ExceptionType {
NOT_FOUND(Status.NOT_FOUND, "These aren't the droids you're looking for!");
private Status status;
private String description;
private ExceptionType(Status status, String description){
this.status = status;
this.description = description;
}
//other methods here..
}
}
我的问题是关于 ExceptionFactory.build(),如何指定 build() 方法的参数,以便第二个参数必须特定于 CustomException 类?
如果这种方法听起来很疯狂,如何改进它?目标是拥有一个通用工厂方法,用于构建已预加载详细信息的异常。我想要避免的是这样的事情..
ExceptionFactory.build(CustomException.class, "Some string...")
想法是描述需要在 CustomException 中定义,而不仅仅是抛出错误时的任何内容。那么如何强制执行呢??
public class ExceptionFactory {
public static <T extends RuntimeException> T build(T e, ???){
//more logic here...
}
}
最佳答案
您可以使用标记界面:
interface ExceptionTypeEnum<T extends RuntimeException> {}
private enum ExceptionType implements ExceptionTypeEnum<CustomException> {
...
}
public static <T extends RuntimeException> T build(T e, ExceptionTypeEnum<T> type) {
关于Java 泛型,强制枚举参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32361901/