Java泛型,实施枚举参数

时间:2015-09-02 19:50:59

标签: java generics enums

我正在构建一个用于生成RuntimeExceptions的工厂方法。

想法是通过执行以下代码片段来抛出异常:

throw ExceptionFactory.build(CustomException.class, CustomException.NOT_FOUND);

构建方法的第一个参数是异常类,但是第二个参数将引用在CustomException类中定义的Enum,以便在构建异常时加载其他详细信息。

示例:

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...
  }

}

3 个答案:

答案 0 :(得分:3)

您可以使用标记界面:

interface ExceptionTypeEnum<T extends RuntimeException> {}

private enum ExceptionType implements ExceptionTypeEnum<CustomException> {
    ...
}

public static <T extends RuntimeException> T build(T e, ExceptionTypeEnum<T> type) {

答案 1 :(得分:1)

实现此方法的一种方法是在您的异常类型中使用工厂方法,而不是使用ExceptionFactory某些东西。例如:

public class CustomException extends RuntimeException {
   private CustomException(String description) {...}
   public static CustomException notFound() {
     return new CustomException("not found");
   }
   ....
}

这可以确保代码的任何CustomException用户来自您使用您选择的信息填充异常消息的工厂方法之一。您还可以将任何参数添加到静态工厂方法中,因此不同的异常原因可能需要在工厂方法中使用不同的参数。

答案 2 :(得分:1)

我不确定我真的看到你打算做什么很有价值。我不清楚生成异常的复杂工厂机制如何在需要的地方和时间直接实例化它们。不过,您可以通过使枚举更具功能来解决此问题。

例如,

public interface ExceptionEnum {
    public Class<? extends RuntimeException> getExceptionClass();
}

public class CustomException extends RuntimeException {

    enum Details implements ExceptionEnum {
        GOOD, BAD, UGLY;

        public Class<? extends RuntimeException> getExceptionClass() {
            return CustomException.class;
        }
    };

    // ...
}

// ...

throw ExceptionFactory.build(CustomException.GOOD);

ExceptionFactory.build()只需要ExceptionEnum类型的参数。