I'm looking to replace the need for separate stand-alone static initialer functions with lambdas. e.g. I'd like to replace something like this...
class Foo {
private static final Set<String> keywords = keywords();
private static Set<String> keywords() {
HashSet<String> s = new HashSet<>();
s.add("AND");
s.add("NOT");
s.add("OR");
return Collections.unmodifiableSet(s);
}
}
With something that invokes a lambda that is defined in place at class load time. Please note, it's not my goal to invoke this lazily.
For the moment, I have created a simple Initializer
class with a static method that accepts a Supplier
, calls it and returns the value.
Initializer
class
public class Initializer {
public static <T> T init(Supplier<T> initializer) {
return initializer.get();
}
}
Then in another class:
import static com.whatever.Initializer.init;
class Foo {
private static final Set<String> keywords = init(() -> {
HashSet<String> s = new HashSet<>();
s.add("AND");
s.add("NOT");
s.add("OR");
return Collections.unmodifiableSet(s);
});
}
Is there something that exists in the standard Java libraries already so that I don't need to provide my own Initializer
class, or is there some way to simply define and then execute a lambda in-place?