在Java中定义常量并在集合中使用它们

时间:2016-12-15 14:01:28

标签: java constants

我有一个类似的课程:

class DomainTypes {
  public static final DomainType DOMAIN_1 = DomainType.of("example1.com");
  public static final DomainType DOMAIN_2 = DomainType.of("example2.com");
  public static final DomainType DOMAIN_3 = DomainType.of("example3.com");

  public static Set<DomainType> getDomainTypes() {
    return ImmutableSet.of(
      DOMAIN_1, DOMAIN_2, DOMAIN_3
    );
  }
}

但这很容易出错。如果有人将域添加为新常量,她可能会忘记将其添加到getDomainTypes()方法中。如果可能,我不想使用反射。

我需要在不同的模块(jar)中使用DomainType类 - 一种API模块 - 让我们说dns-api模块,而不是DomainTypes。 DomainTypes是相当配置的,它位于web-app模块中,它依赖于dns-api模块。使用枚举,我无法使用实现的逻辑将配置与对象分开,我也无法在另一个应用程序中重用dns-api模块。所以我认为使用enum不是我的解决方案。

1 个答案:

答案 0 :(得分:1)

使用enum而不是具有常量的类:

public enum DomainType {
    DOMAIN_1("example1.com"),
    DOMAIN_2("example2.com"),
    DOMAIN_3("example3.com");

    private final String url;

    DomainType(String url) {
        this.url = url;
    }

    public String getUrl() {
        return url;
    }
}

枚举自动拥有values()方法,该方法为您提供所有值的数组:

DomainType[] domainTypes = DomainType.values();