public class ConfigOption<T> {
private final String key;
private final T defaultValue;
private final String description;
public ConfigOption(String key, T defaultValue) {
this.key = checkNotNull(key);
this.description = "";
this.defaultValue = defaultValue;
}
public ConfigOption(String key, String description, T defaultValue) {
this.key = checkNotNull(key);
this.description = description;
this.defaultValue = defaultValue;
}
public ConfigOption<T> withDescription(final String description) {
return new ConfigOption<>(key, description, defaultValue);
}
public String key() {
return key;
}
public boolean hasDefaultValue() {
return defaultValue != null;
}
public T defaultValue() {
return defaultValue;
}
public String description() {
return description;
}
public static <T> T checkNotNull(T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
else if (o != null && o.getClass() == ConfigOption.class) {
ConfigOption<?> that = (ConfigOption<?>) o;
return this.key.equals(that.key) &&
(this.defaultValue == null ? that.defaultValue == null :
(that.defaultValue != null && this.defaultValue.equals(that.defaultValue)));
}
else {
return false;
}
}
@Override
public int hashCode() {
return 31 * key.hashCode() +
(defaultValue != null ? defaultValue.hashCode() : 0);
}
@Override
public String toString() {
return String.format("Key: '%s' , default: %s", key, defaultValue);
}
}
定義的配置項
public class ConfOptions {
public static final ConfigOption<String> PROJECT_KEY =
key("project.key")
.defaultValue("")
.withDescription("key的描述內容");
/**
* 項目中使用的配置中心key的集合
*/
public static List<ConfigOption> BASIC_OPTION = new ArrayList<>();
static {
BASIC_OPTION.add(PROJECT_KEY);
}
public static OptionBuilder key(String key) {
checkNotNull(key);
return new OptionBuilder(key);
}
public static final class OptionBuilder {
private final String key;
OptionBuilder(String key) {
this.key = key;
}
public <T> ConfigOption<T> defaultValue(T value) {
checkNotNull(value);
return new ConfigOption<>(key, value);
}
public ConfigOption<String> noDefaultValue() {
return new ConfigOption<>(key, null);
}
}
}