【问题标题】:How to add constant to enum?如何向枚举添加常量?
【发布时间】:2022-01-18 16:37:17
【问题描述】:

我有一个带有一些链接的枚举。在这些链接中是相同的版本号(1.1.1),现在作为一个字符串,我想用常量替换它。这个怎么做? 我可以在返回链接时编辑链接(用我的常量替换一些字符串),但这似乎不是干净的解决方案。感谢您的帮助!

package test.intro;

import test.version;

public enum LinkType
{
  LINK1("test/1.1.1/doc/test1.pdf"),
  LINK2("test/1.1.1/doc/test2.pdf"),
  LINK3("test/1.1.1/doc/test3.pdf");
  
  public final String href;
  //my constant I want to use:
  private final String versionName = version.getVersionName();

  private LinkType(String href)
  {
    this.href = href;
  }

  public String getHref()
  {
    return href;
  }

}

【问题讨论】:

  • 为什么?如果它对所有枚举都具有相同的值,为什么要在其中拥有它
  • @Stultuske 嗨,因为在test.version 我可以在一天更新版本,我不想手动更新枚举中的所有链接。

标签: java enums


【解决方案1】:

我将我的枚举放入新类并创建了一个属性。因为我的枚举只在一种方法中被调用,所以很容易改变。 @David Mališ 的解决方案可能更干净。

package test.intro;

import test.version;

public class TestLinks {
  private final static String versionName = version.getVersionName();

  public enum LinkType {
    LINK1("test/"+versionName+"/doc/test1.pdf"),
      
    //another code
  }
}

【讨论】:

    【解决方案2】:

    我猜version.getVersionName() 是静态方法?

    那么你可以写LINK1("test/" + version.getVersionName() + "/doc/test1.pdf")等。

    【讨论】:

    • 感谢@user3768649,但也许最好只调用一次version.getVersionName() 并创建一些常量?
    • 如果version.getVersionName() 后面有一个昂贵的调用,我相信version 类应该处理将其保存为常量。您的枚举不需要关注这一点。如果version.getVersionName() 后面没有昂贵的调用,则不需要常量。
    【解决方案3】:

    你可以这样做:

    package test.intro;
    
    import test.version;
    
    public enum LinkType {
    
      LINK1("test/%s/doc/test1.pdf"),
      LINK2("test/%s/doc/test2.pdf"),
      LINK3("test/%s/doc/test3.pdf");
    
      public final String hrefTemplate;
    
      private LinkType(String hrefTemplate) {
        this.hrefTemplate = hrefTemplate;
      }
    
      public String getHrefTemplate() {
          return this.hrefTemplate;
      }
    
      public String getHref() {
        return String.format(this.hrefTemplate, version.getVersionName());
        // or return this.hrefTemplate.formatted(version.getVersionName()); if you have Java >= 13
    
      }
    
    }
    

    【讨论】:

    • 或使用有问题的常量:this.hrefTemplate.formatted(versionName);;甚至在构造函数中:this.href = hrefTemplate.formatted(versionName);
    • @user16320675 是的 :) 取决于您想要什么以及 getVersionName() 方法的真正作用。但你是绝对正确的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-24
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 2011-08-17
    • 1970-01-01
    • 2020-12-24
    相关资源
    最近更新 更多