Java 泛型,强制枚举参数

标签 java generics enums

我正在尝试构建一个用于生成 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/

相关文章:

javascript - 这是实现枚举的正确方法吗?

java - Selenium WebDriverWait.until(invisiblityOfAllElements) 在 NoSuchElementException 上返回超时

java - 相当于JDIC?

java - 我应该在 if-else block 中抛出异常吗?

java - Java中with extend有哪些方法可以设置上限

Java 枚举构造函数未定义

java - 使用正则表达式查找字符串中的所有字母

c# - 我可以在 MethodInfo 对象上找到应用的泛型参数的位置吗?

java 声明一个泛型数组

enums - 我可以用它的数值设置一个枚举吗?