I\'ve added a human-readable configuration file to my app using java.util.Properties and am trying to add a wrapper around it to make type conversions easier. Specifically,
The following uses functional interfaces.
You could change the method signature to use a provided "parser":
protected T getProperty(String key, T fallback, Function parser) {
String value = properties.getProperty(key);
if (value == null) {
return fallback;
} else {
return parser.apply(value);
}
}
Also, for efficiency you might want to replace T fallback
with Supplier extends T> fallbackSupplier
to prevent having to create fallback values when they are not needed:
protected T getProperty(String key, Supplier extends T> fallbackSupplier, Function parser) {
String value = properties.getProperty(key);
if (value == null) {
return fallbackSupplier.get();
} else {
return parser.apply(value);
}
}
Then you can use method references and lambda expressions as parser and fallback supplier, e.g.:
protected void func2() {
foobar = getProperty("foobar", () -> 210, Integer::valueOf);
// Better create own parsing method which properly handles
// invalid boolean strings instead of using Boolean#valueOf
foobaz = getProperty("foobaz", () -> true, Boolean::valueOf);
// Imagine creation of `ExpensiveObject` is time-wise or
// computational expensive
bar = getProperty("bar", ExpensiveObject::new, ExpensiveObject::parse);
}
The advantage of this approach is that it is not restricted to a (potentially non-existent) constructor anymore.