简体   繁体   English

像吸气剂一样使用枚举?

[英]Use enum like a getter?

I have a util class that keeps track of important system variables: 我有一个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);
}

And I can retrieve these values like so: 我可以像这样检索这些值:

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

Is it possible, in Java, to get these like an enum? 在Java中,是否有可能像枚举一样获取它们?

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

String port = SystemPropertyHelper.REQUEST_PORT;

我会这样解决的。

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

            private String key;

            Config(String key) {
                this.key = key;
            }

            public String get() {
             return System.getProperty(key);
            }
        }

and use it like SystemPropertyHelper.REQUEST_PORT.get(); 并像SystemPropertyHelper.REQUEST_PORT.get();一样使用它

Sure, you could create an enum like this, which would give you access to the property name, and the value: 当然,您可以创建一个这样的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;
    }
}

However, you could avoid the need to call a getter by just using public static final String variables for your properties, as @halloei suggests. 但是,就像@halloei所建议的那样,您可以仅通过对属性使用public static final String变量来避免调用getter。

Also you can do something like this: 您也可以执行以下操作:

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

This can be use like: 可以这样使用:

String port = Properties.REQUEST_PORT.getValue();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM