首页 > 解决方案 > 在Java中通过枚举值参数化类型?

问题描述

我正在研究使用 Enum 值对 Java 中的泛型类进行参数化,以提高类型安全性和一些编译时检查(我知道泛型参数在运行时被擦除)。

前提

使用表单的枚举(来自外部依赖项,我无法更改)

enum VehicleType {
  CAR(1),
  MOTORCYCLE(2),
  BIKE(3);

  int id;

  VehicleType(int n) {
    id = n;
  }
}

目标

我想表达以下内容:

/*                 vvvvvvvvv--------------- this is pseudocode here */
class Inventory<VT member of VehicleType> {
  private int amount;
  Inventory<VT>(int n){
    if (n < 0) throw new Exception();
    amount = n;
  }
  int getAmount() { return amount; }

  // This is the crucial part where we would gain something
  // from compile time type checking
  Inventory<VT> add(Inventory<VT> items) {
    return new Inventory<VT>(this.getAmount() + items.getAmount());
  }
}

现在,显然在 Enum 的定义编译时,我的问题所涉及的第二个代码块不能(这就是我问的原因)。

类型安全将来自在类型级别隐式匹配库存项目的“单位”或“类型”(在此示例中),在编译时捕获不匹配。

按照惯例,如果我定义了一个字段private VehicleType vt;并在构造函数中显式设置它,我必须检查方法中的匹配类型add(...)并抛出一个需要在其他地方处理的异常。

问题

主要问题

我能以某种方式在 Java 8 中获得这种预想的类型安全吗?有没有成语(理想情况下没有过多的样板)?

奖金问题

Java 11 有可能吗?

标签: javagenericsgeneric-programmingtype-safety

解决方案


推荐阅读