【问题标题】:Use enum like a getter?像 getter 一样使用枚举?
【发布时间】:2016-05-15 12:02:49
【问题描述】:

我有一个跟踪重要系统变量的 util 类:

public static final String REQUEST_ADDRESS = "http.request.address";  
public static final String REQUEST_PORT = "http.request.port";

public static final String get(String property) {
    return System.getProperty(property);
}

我可以像这样检索这些值:

String port = SystemPropertyHelper.get(SystemPropertyHelper.REQUEST_PORT);

是否有可能在 Java 中像枚举一样获取这些?

REQUEST_PORT {
    return System.getProperty("http.request.port");
}

String port = SystemPropertyHelper.REQUEST_PORT;

【问题讨论】:

  • 字符串常量有什么问题?
  • 这不会阻止该值的变化被拾取吗? (即使更改这些值是一种反模式)
  • 我喜欢将接口用于常量,因为您不必键入public static final 修饰符。考虑一下。持续节省大约 2 秒!
  • @IVRAvenger 所以你想用枚举来存储一些可变数据?

标签: java enums syntactic-sugar


【解决方案1】:

我会这样解决的。

public static final String REQUEST_PORT = System.getProperty("http.request.port");

【讨论】:

    【解决方案2】:
            enum SystemPropertyHelper {
                REQUEST_PORT("http.request.port"), ...;
    
                private String key;
    
                Config(String key) {
                    this.key = key;
                }
    
                public String get() {
                 return System.getProperty(key);
                }
            }
    

    并像SystemPropertyHelper.REQUEST_PORT.get();一样使用它

    【讨论】:

      【解决方案3】:

      当然,您可以像这样创建enum,这样您就可以访问属性名称和值:

      public enum SystemPropertyEnum {
          REQUEST_PORT("http.request.port"),
          REQUEST_ADDRESS("http.request.address");
      
          private String propertyName;
          private String value;
      
          SystemPropertyEnum(final String propertyName) {
              this.propertyName = propertyName;
              this.value = System.getProperty(propertyName);
          }
      
          public String getPropertyName() {
              return propertyName;
          }
      
          public String getValue() {
              return value;
          }
      }
      

      但是,正如@halloei 所建议的那样,您可以通过为您的属性使用public static final String 变量来避免调用getter。

      【讨论】:

        【解决方案4】:

        你也可以这样做:

        public enum Properties {
            REQUEST_PORT("http.request.port"),
            REQUEST_USE_SSL("http.request.ssl");
            // Add others...
        
            private final String value;
        
            Properties(String value) {
                this.value = System.getProperty(value);
            }
        
            public String getValue() {
                return this.value;
            }
        }
        

        这可以像这样使用:

        String port = Properties.REQUEST_PORT.getValue();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-10-30
          • 2010-09-17
          • 1970-01-01
          • 1970-01-01
          • 2012-08-24
          • 1970-01-01
          相关资源
          最近更新 更多