[英]Use enum like a getter?
我有一个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 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);
}
}
并像SystemPropertyHelper.REQUEST_PORT.get();
一样使用它
当然,您可以创建一个这样的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。
您也可以执行以下操作:
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.